ajaxFileUpload 异步上传文件简单使用

来源:互联网 发布:公章制作软件apk 编辑:程序博客网 时间:2024/06/05 13:28

ajaxFileUpload 异步上传文件简单使用

原创 2014年07月18日 17:36:26
[html] view plain copy
  1.   
[html] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Insert title here</title>  
  8.   
  9. <!-- 引用jquery -->  
  10. <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>  
  11. <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>  
  12.   
  13. <!-- 引用ajaxfileupload.js -->  
  14. <script src="../js/ajaxfileupload.js"></script>  
  15.   
  16. <script type="text/javascript">  
  17. $(function(){  
  18.     //点击打开文件选择器  
  19.     $("#upload").on('click', function() {  
  20.         $('#fileToUpload').click();  
  21.     });  
  22.       
  23.     //选择文件之后执行上传  
  24.     $('#fileToUpload').on('change', function() {  
  25.         $.ajaxFileUpload({  
  26.             url:'../FileUploadServlet',  
  27.             secureuri:false,  
  28.             fileElementId:'fileToUpload',//file标签的id  
  29.             dataType: 'json',//返回数据的类型  
  30.             data:{name:'logan'},//一同上传的数据  
  31.             success: function (data, status) {  
  32.                 //把图片替换  
  33.                 var obj = jQuery.parseJSON(data);  
  34.                 $("#upload").attr("src", "../image/"+obj.fileName);  
  35.       
  36.                 if(typeof(data.error) != 'undefined') {  
  37.                     if(data.error != '') {  
  38.                         alert(data.error);  
  39.                     } else {  
  40.                         alert(data.msg);  
  41.                     }  
  42.                 }  
  43.             },  
  44.             error: function (data, status, e) {  
  45.                 alert(e);  
  46.             }  
  47.         });  
  48.     });  
  49.       
  50. });  
  51. </script>  
  52.   
  53. </head>  
  54. <body>  
  55.   
  56. <!-- 点击图片,打开文件选择器,确定,上传。(这是网络上的一个图片) -->  
  57. <img id="upload" alt="" style="width: 200px; height: 200px"  
  58.     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">  
  59.   
  60. <!-- 隐藏file标签 -->  
  61. <input id="fileToUpload" style="display: none" type="file" name="upfile"><br/>  
  62.     
  63. </body>  
  64. </html>  


[java] view plain copy
  1. package com.yangshidesign.weixinface.servlet;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletContext;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.annotation.WebServlet;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.apache.commons.fileupload.FileItem;  
  15. import org.apache.commons.fileupload.FileUploadException;  
  16. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  17. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  18.   
  19. import com.alibaba.fastjson.JSONObject;  
  20.   
  21. /** 
  22.  * Servlet implementation class FileUploadServlet 
  23.  */  
  24. @WebServlet("/FileUploadServlet")  
  25. public class FileUploadServlet extends HttpServlet {  
  26.     private static final long serialVersionUID = 1L;  
  27.   
  28.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  29.         response.getWriter().println("ppppppppppppppppppp");  
  30.     }  
  31.   
  32.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  33.         //需要返回的fileName  
  34.         String fileName = null;  
  35.           
  36.         //参考资料  http://commons.apache.org/proper/commons-fileupload/using.html  
  37.         // Check that we have a file upload request  
  38.         boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  39.           
  40.         // Create a factory for disk-based file items  
  41.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  42.   
  43.         // Configure a repository (to ensure a secure temp location is used)  
  44.         ServletContext servletContext = this.getServletConfig().getServletContext();  
  45.         File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");  
  46.         factory.setRepository(repository);  
  47.   
  48.         // Create a new file upload handler  
  49.         ServletFileUpload upload = new ServletFileUpload(factory);  
  50.   
  51.         // Parse the request  
  52.         try {  
  53.             List<FileItem> items = upload.parseRequest(request);  
  54.             for(FileItem item : items) {  
  55.                 //其他参数  
  56.                 String type = item.getContentType();  
  57.                 if(type == null) {  
  58. //                  System.out.println(item.getString(item.getFieldName()));  
  59.                     continue;  
  60.                 }  
  61.                   
  62.                 //文件参数  
  63.                 fileName = item.getName();  
  64.                   
  65.                 //设置保存文件路径  
  66.                 String realPath = request.getServletContext().getRealPath("/image");  
  67.                 File dir = new File(realPath);  
  68.                 File f = new File(dir, fileName);  
  69.                   
  70.                 if(f.exists()) {  
  71.                     f.delete();  
  72.                 }  
  73.                 f.createNewFile();  
  74.                   
  75.                 //保存  
  76.                 item.write(f);  
  77.                   
  78.             }  
  79.         } catch (FileUploadException e) {  
  80.             e.printStackTrace();  
  81.         } catch (Exception e) {  
  82.             e.printStackTrace();  
  83.         }  
  84.           
  85.         //返回结果  
  86.         JSONObject obj = new JSONObject();  
  87.         obj.put("fileName", fileName);  
  88.         response.getWriter().print(obj.toJSONString());  
  89.     }  
  90.   
  91. }  

需要用到的一个js文件:(点击下载)

ajaxfileupload.js

两个jar包:

commons-io-2.4.jar

commons-fileupload-1.3.1.jar


注意:上传成功之后没有执行回调函数。

解决方法:(参考链接:http://www.myexception.cn/ajax/727453.html)

打开ajaxfileupload.js拉到底下找到

[javascript] view plain copy
  1. if ( type == "json" ) {  
  2.             eval( "data = " + data );  
  3.         }     

改成:

[javascript] view plain copy
  1. if ( type == "json" ) {  
  2.             data = data.replace("<pre>","").replace("</pre>","");  
  3.             //data = eval("("+data.replace("<pre>","").replace("</pre>","")+")");  
  4.         }     


版权声明:本文为博主原创文章,转载请注明原地址。
 
ma15732625261
  • ma15732625261

    2017-03-18 21:2713楼
  • ajaxFileUpload 异步上传文件简单使用,兼容性不太好
  • 回复
kookkj
  • kookkj

    2016-10-27 11:1312楼
  • 怒赞
  • 回复
laizhiming1989
  • laizhiming1989

    2016-01-14 12:0911楼
  • [html] view plain copy
    1. <pre style="word-wrap: break-word; white-space: pre-wrap;">  


    这个怎么过滤?
  • 回复
a708856902
  • a708856902

    2016-01-13 14:5710楼
  • 抄东西都抄不全,真是醉了,你确定最后你的替换内容有效?白让我找了半天
  • 回复 
qiantujava
qq_32901793
  • qq_32901793

    2015-11-18 10:169楼
  • 能发我一份吗854580614@qq.com
原创粉丝点击