首页 > 代码库 > JQuery 实现文件上传

JQuery 实现文件上传

简述:

实现前端使用jquery上传文件

后台用servlet处理文件上传以及保存


知识点:

1. 用到ajaxfileupload.js库

2. 后台servlet文件保存


其中ajaxfileupload的库下载地址:

http://www.phpletter.com/download_project_version.php?version_id=34


Maven中需要添加两个java的库,用来上传以及在服务器保存文件

[html] view plaincopy

  1. <dependency>  

  2.     <groupId>commons-fileupload</groupId>  

  3.     <artifactId>commons-fileupload</artifactId>  

  4.     <version>1.2.2</version>  

  5. </dependency>  

  6. <dependency>  

  7.     <groupId>org.apache.commons</groupId>  

  8.     <artifactId>commons-io</artifactId>  

  9.     <version>1.3.2</version>  

  10. </dependency>  




项目结构(主要是js)



testUpload.html

[html] view plaincopy

  1. <!DOCTYPE html>  

  2. <head>  

  3. <title>MyWebProject</title>  

  4. <meta charset="utf-8" />  

  5. <link type="text/css" href="./lib/css/jquery-ui-1.8.19.custom.css"  

  6.     rel="stylesheet" />  

  7.     <link type="text/css" href="./lib/css/ajaxfileupload.css"  

  8.     rel="stylesheet" />  

  9. <script type="text/javascript" src="./lib/js/jquery-1.8.3.js"></script>  

  10. <script type="text/javascript" src="./lib/js/ajaxfileupload.js"></script>  

  11. <script type="text/javascript">  

  12. function ajaxFileUpload() {  

  13.     $.ajaxFileUpload({  

  14.         url : "./UploadFile",   //submit to UploadFileServlet  

  15.         secureuri : false,  

  16.         fileElementId : ‘fileToUpload‘,  

  17.         dataType : ‘text‘, //or json xml whatever you like~  

  18.         success : function(data, status) {  

  19.             $("#result").append(data);  

  20.         },  

  21.         error : function(data, status, e) {  

  22.             $("#result").append(data);  

  23.         }  

  24.     });  

  25.     return false;  

  26. }  

  27. </script>  

  28. </head>  

  29.   

  30. <body>  

  31.     <!-- upload file -->  

  32.     <form name="form" action="./UploadFile" method="POST" enctype="multipart/form-data">  

  33.         <table class="tableForm">  

  34.             <thead>  

  35.                 <tr>  

  36.                     <th>JQuery Ajax File Upload</th>  

  37.                 </tr>  

  38.             </thead>  

  39.             <tbody>  

  40.                 <tr>  

  41.                     <td><input id="fileToUpload"  type="file" size="45"   

  42.                         name="fileToUpload"  class="input"></td>  

  43.                 </tr>  

  44.             </tbody>  

  45.             <tfoot>  

  46.                 <tr>  

  47.                     <td><button class="button" id="buttonUpload"  

  48.                             onclick="return ajaxFileUpload();">Upload</button></td>  

  49.                 </tr>  

  50.             </tfoot>  

  51.         </table>  

  52.         <div id="result" style="margin-left:200px"></div>  

  53.     </form>  

  54. </body>  

  55. </html>  


后台实现:

参考:http://blog.163.com/lin305_gf/blog/static/969524402011718102116625/

UploadFileServlet.java

[java] view plaincopy

  1. package mwp.servlet;  

  2.   

  3. import java.io.File;  

  4. import java.io.IOException;  

  5. import java.util.Iterator;  

  6.   

  7. import javax.servlet.ServletException;  

  8. import javax.servlet.http.HttpServlet;  

  9. import javax.servlet.http.HttpServletRequest;  

  10. import javax.servlet.http.HttpServletResponse;  

  11.   

  12. import org.apache.commons.fileupload.FileItem;  

  13. import org.apache.commons.fileupload.FileItemFactory;  

  14. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  

  15. import org.apache.commons.fileupload.servlet.ServletFileUpload;  

  16. import org.slf4j.Logger;  

  17. import org.slf4j.LoggerFactory;  

  18.   

  19. /** 

  20.  * Servlet implementation class UploadFileServlet 

  21.  */  

  22. public class UploadFileServlet extends HttpServlet {  

  23.     private static final long serialVersionUID = 1L;  

  24.     private static Logger logger = LoggerFactory.getLogger(UploadFileServlet.class);  

  25.   

  26.     /** 

  27.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 

  28.      */  

  29.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

  30.         request.setCharacterEncoding("utf-8");  

  31.         //判断提交过来的表单是否为文件上传菜单  

  32.         boolean isMultipart= ServletFileUpload.isMultipartContent(request);  

  33.         if(isMultipart){  

  34.             //构造一个文件上传处理对象  

  35.             FileItemFactory factory = new DiskFileItemFactory();  

  36.             ServletFileUpload upload = new ServletFileUpload(factory);  

  37.   

  38.             Iterator items;  

  39.             try{  

  40.                 //解析表单中提交的所有文件内容  

  41.                 items = upload.parseRequest(request).iterator();  

  42.                 while(items.hasNext()){  

  43.                     FileItem item = (FileItem) items.next();  

  44.                     if(!item.isFormField()){  

  45.                         //取出上传文件的文件名称  

  46.                         String name = item.getName();  

  47.                         //取得上传文件以后的存储路径  

  48.                         String fileName = name.substring(name.lastIndexOf(‘\\‘) + 1, name.length());  

  49.                         //上传文件以后的存储路径  

  50.                         String saveDir = this.getServletContext().getRealPath("/upload/");  

  51.                         if (!(new File(saveDir).isDirectory())){  

  52.                             new File(saveDir).mkdir();  

  53.                         }  

  54.                         String path= saveDir + File.separatorChar + fileName;  

  55.   

  56.                         //上传文件  

  57.                         File uploaderFile = new File(path);  

  58.                         item.write(uploaderFile);  

  59.                     }  

  60.                 }  

  61.             }catch(Exception e){  

  62.                 e.printStackTrace();  

  63.                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);    

  64.                 return;    

  65.             }  

  66.             response.setStatus(HttpServletResponse.SC_OK);  

  67.             response.getWriter().append("Success Upload");  

  68.         }   

  69.     }   

  70. }  


测试界面:


如若数据交换格式是JSON,则如下示例

JS

[javascript] view plaincopy

  1. /** 

  2.  * 上传图片 

  3.  */  

  4. function uploadUnitImage()  {  

  5.         showLoading("正在上传,请等待...");  

  6.         $.ajaxFileUpload  

  7.         (  

  8.             {  

  9.                 url:‘/my-web/fileUpload?action=uploadImage‘,//用于文件上传的服务器端请求地址,目前与优惠券上传图片请求地址一致  

  10.                 secureuri:false,//一般设置为false  

  11.                 fileElementId: ‘unitImageToUpload‘//文件上传空间的id属性  

  12.                 dataType: ‘json‘,//返回值类型 一般设置为json  

  13.                 success: function (data, status)  //服务器成功响应处理函数  

  14.                 {  

  15.                     if(typeof(data.error) != ‘undefined‘)  

  16.                     {  

  17.                         if(data.error != ‘‘)  

  18.                         {  

  19.                             alert(data.error);  

  20.                             dismissLoading();  

  21.                         }else  

  22.                         {  

  23.                             //若上传成功则自定义一些事  

  24.                             // do something  

  25.                         }  

  26.                     }  

  27.                 },  

  28.                 error: function (data, status, e)//服务器响应失败处理函数  

  29.                 {  

  30.                     alert(e);  

  31.                     dismissLoading();  

  32.                 }  

  33.             }  

  34.         )  

  35. }  



JAVA

[java] view plaincopy

  1. public void uploadImage(  

  2.         HttpServletRequest request,HttpServletResponse response) throws Exception{  

  3.     logger.debug("上传图片");  

  4.     //上传图片  

  5.     String fileUrl=uploadFileAndGetFileUrl(request);  

  6.     String responseText = "";  

  7.     if(!StringUtils.isEmpty(fileUrl)){  

  8.         logger.debug("图片下载地址是"+fileUrl);  

  9.          responseText="{error: ‘‘,url: ‘"+fileUrl+"‘}";  

  10.     }else{  

  11.         logger.debug("账户创建页面,图片上传失败");  

  12.         responseText="{error: ‘‘}";  

  13.     }  

  14.       

  15.     responseOutWithText(response, responseText);  

  16. }  


由于AjaxFileUpload在解析返回的response若为JSON数据时会出现问题,所以需要转为text

[java] view plaincopy

  1. /** 

  2.  * 以文本形式下发数据 

  3.  * @param response 

  4.  * @param responseText 

  5.  */  

  6. protected void responseOutWithText(HttpServletResponse response,  

  7.         String responseText) {  

  8.     response.setCharacterEncoding("UTF-8");  

  9.     response.setContentType("text/html");  

  10.     PrintWriter out = null;  

  11.     try {  

  12.         out = response.getWriter();  

  13.         out.println(responseText);  

  14.         out.close();  

  15.         logger.debug("下发的数据是");  

  16.         logger.debug(responseText);  

  17.     } catch (IOException e) {  

  18.         // TODO Auto-generated catch block  

  19.         e.printStackTrace();  

  20.     } finally {  

  21.         if (out != null) {  

  22.             out.close();  

  23.         }  

  24.     }  

  25. }  



JQuery 实现文件上传