学会上传图片
Q1:需要导入到包
需要的联系我,我发给你。(里面需要的包和文件确实有点多)
layui,jquery
当然还要有images文件
序列化文件
lib里面
总图片:
Q2:html文件(NewFile.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<link rel="stylesheet" href="js/layui/css/layui.css">
<body>
<script type="text/javascript" src="js/jquery-1.11.3.js" ></script>
<script src="js/layui/layui.js"></script>
<div class="layui-upload">
<button type="button" class="layui-btn" id="test1">上传图片</button>
<div class="layui-upload-list">
<img class="layui-upload-img" id="demo1" style="border:1px solid red;width:100px;height:100px">
<p id="demoText"></p>
</div>
</div>
<script>
//图片上传
layui.use('upload', function(){
var $ = layui.jquery
,upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
elem: '#test1'
,url: 'UploadFile'
,before: function(obj){
//预读本地文件示例,不支持ie8
obj.preview(function(index, file, result){
$('#demo1').attr('src', result); //图片链接(base64)
});
}
,done: function(res){
//如果上传失败
if(res.code > 0){
return layer.msg('上传失败');
}
//上传成功
layer.msg(res.msg);
urls=res.data.name;
$("#demo1").style.backgroundImage="";
}
,error: function(){
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
demoText.find('.demo-reload').on('click', function(){
uploadInst.upload();
});
}
});
});
</script>
</body>
</html>
Q3:servlet(UploadFile)
package com.action; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.vo.R; import com.vo.Rs; import jsonUtil.JsonUtils; /** * Servlet implementation class UploadFile */ @WebServlet("/UploadFile") public class UploadFile extends HttpServlet { private static final long serialVersionUID = 1L; public UploadFile() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码 response.setCharacterEncoding("utf-8"); // 物理路径 String savePath = this.getServletConfig().getServletContext().getRealPath(""); savePath = savePath + "images\\";//我所要放的绝对路径的位置 File f1 = new File(savePath); if (!f1.exists()) { f1.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8"); List<FileItem> fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException ex) { return; } Iterator<FileItem> it = fileList.iterator(); String name = ""; String extName = ""; while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { name = item.getName(); long size = item.getSize(); String type = item.getContentType(); //System.out.println(size + " " + type); if (name == null || name.trim().equals("")) { continue; } // 扩展名格式: if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } File file = null; do { // 生成文件名: name = UUID.randomUUID().toString(); file = new File(savePath + name + extName); } while (file.exists()); File saveFile = new File(savePath + name + extName); try { item.write(saveFile); } catch (Exception exp) { response.getWriter().write(exp.getMessage()); exp.printStackTrace(); } } } R r = new R(); r.setCode(0); r.setMsg("上传成功"); Map<String, String> data = new HashMap<String, String>(); data.put("src", "images/" + name + extName); data.put("name",name + extName); r.setData(data); response.getWriter().print(JsonUtils.toJson(r)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Q4:实体类
package com.vo; public class R { /**响应编码*/ private int code; /**响应消息*/ private String msg; /**数据总量*/ private int count; /**数据*/ private Object data; public R() {} public R(int code, String msg, int count, Object data) { super(); this.code = code; this.msg = msg; this.count = count; this.data = data; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } @Override public String toString() { return "R [code=" + code + ", msg=" + msg + ", count=" + count + ", data=" + data + "]"; } }
结果展示:
以上便是上传图片的所有代码,希望大家都能学会
zywds