<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <!-- 引用jquery --> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <!-- 引用ajaxfileupload.js --> <script src="../js/ajaxfileupload.js"></script> <script type="text/javascript"> $(function(){ //点击打开文件选择器 $("#upload").on('click', function() { $('#fileToUpload').click(); }); //选择文件之后执行上传 $('#fileToUpload').on('change', function() { $.ajaxFileUpload({ url:'../FileUploadServlet', secureuri:false, fileElementId:'fileToUpload',//file标签的id dataType: 'json',//返回数据的类型 data:{name:'logan'},//一同上传的数据 success: function (data, status) { //把图片替换 var obj = jQuery.parseJSON(data); $("#upload").attr("src", "../image/"+obj.fileName); if(typeof(data.error) != 'undefined') { if(data.error != '') { alert(data.error); } else { alert(data.msg); } } }, error: function (data, status, e) { alert(e); } }); }); }); </script> </head> <body> <!-- 点击图片,打开文件选择器,确定,上传。(这是网络上的一个图片) --> <img id="upload" alt="" style="width: 200px; height: 200px" src="http://d.pcs.baidu.com/thumbnail/e8119cd92364a9b2714ea0a92af15aec?fid=2399642819-250528-305026848845811&time=1405674000&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-abo3xnZkLb7yMEPLDWiuaQI8kXM%3D&rt=sh&expires=2h&r=900585425&sharesign=unknown&size=c710_u500&quality=100"> <!-- 隐藏file标签 --> <input id="fileToUpload" style="display: none" type="file" name="upfile"><br/> </body> </html>
package com.yangshidesign.weixinface.servlet; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletContext; 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.alibaba.fastjson.JSONObject; /** * Servlet implementation class FileUploadServlet */ @WebServlet("/FileUploadServlet") public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("ppppppppppppppppppp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //需要返回的fileName String fileName = null; //参考资料 http://commons.apache.org/proper/commons-fileupload/using.html // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(request); for(FileItem item : items) { //其他参数 String type = item.getContentType(); if(type == null) { // System.out.println(item.getString(item.getFieldName())); continue; } //文件参数 fileName = item.getName(); //设置保存文件路径 String realPath = request.getServletContext().getRealPath("/image"); File dir = new File(realPath); File f = new File(dir, fileName); if(f.exists()) { f.delete(); } f.createNewFile(); //保存 item.write(f); } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } //返回结果 JSONObject obj = new JSONObject(); obj.put("fileName", fileName); response.getWriter().print(obj.toJSONString()); } }
需要用到的一個js檔案:(點擊下載)
ajaxfileupload.js
兩個jar包:
commons-io-2.4.jar
commons-io-2.4.jar
注意:上傳成功之後沒有執行回呼函數。
打開ajaxfileupload.js拉到底下找到
if ( type == "json" ) { eval( "data = " + data ); }
改成:
if ( type == "json" ) { data = data.replace("<pre class="brush:php;toolbar:false">","").replace("",""); //data = eval("("+data.replace("
","").replace("","")+")"); }🎜🎜