SpringMVC结合ajaxfileupload文件无刷新上传

jQuery没有提供ajax的文件上传,我们可以通过ajaxfileupload实现ajax文件的上传。其实ajaxfileupload文件上传特别的简单。下面就演示一下在SpringMVC中实现ajax的文件上传。

      1、后台接收代码

     首先在spring的配置文件中添加文件上传配置

     

[html]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.      <!-- 文件上传 -->  
  2. lt;bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  3. <property name="defaultEncoding" value="UTF-8"/>    
  4. lt;/bean>  

 

    再写文件接收的代码

       

[java]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package org.andy.controller;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.Arrays;  
  6. import java.util.Date;  
  7. import java.util.HashMap;  
  8.   
  9. import javax.servlet.ServletContext;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  14. import org.apache.log4j.Logger;  
  15. import org.springframework.stereotype.Controller;  
  16. import org.springframework.web.bind.annotation.RequestMapping;  
  17. import org.springframework.web.bind.annotation.RequestMethod;  
  18. import org.springframework.web.bind.annotation.RequestParam;  
  19. import org.springframework.web.multipart.commons.CommonsMultipartFile;  
  20.   
  21.   
  22. @Controller  
  23. @RequestMapping("/upload")  
  24. public class UploadController {  
  25.   
  26.     private static final Logger LOG = Logger.getLogger(UploadController.class);  
  27.   
  28.     private static final HashMap<String, String> TypeMap = new HashMap<String, String>();  
  29.   
  30.     static {  
  31.         TypeMap.put("image""gif,jpg,jpeg,png,bmp");  
  32.         TypeMap.put("flash""swf,flv");  
  33.         TypeMap.put("media""swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");  
  34.         TypeMap.put("file""doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");  
  35.     }  
  36.   
  37.     /** 
  38.      * 文件上传 之 图片上传 
  39.      *  
  40.      * @param file 
  41.      * @param request 
  42.      * @return message: -1 没有文件上传 0 上传成功 1 上传失败 2 文件超过上传大小 3 文件格式错误 4 上传文件路径非法 5 上传目录没有写权限 
  43.      *        
  44.      *  
  45.      */  
  46.     @RequestMapping(value = "/imageUpload", method = RequestMethod.POST)  
  47.     public void imageUpload(  
  48.             @RequestParam("file") CommonsMultipartFile file,  
  49.             @RequestParam(required = false) String filePre, HttpServletRequest request, HttpServletResponse response) {  
  50.         LOG.info("file name is :" + file.getOriginalFilename());  
  51.           
  52.         if (!file.isEmpty()) {  
  53.             ServletContext servletContext = request.getSession()  
  54.                     .getServletContext();  
  55.             String uploadPath = servletContext.getRealPath("/")  
  56.                     + "uploadImage/";  
  57.             // 文件上传大小  
  58.             long fileSize = 3 * 1024 * 1024;  
  59.   
  60.             if (file.getSize() > fileSize) {  
  61.                 backInfo(response, false2"");  
  62.                 return;  
  63.             }  
  64.   
  65.             String OriginalFilename = file.getOriginalFilename();  
  66.   
  67.             String fileSuffix = OriginalFilename.substring(  
  68.                     OriginalFilename.lastIndexOf(".") + 1).toLowerCase();  
  69.             if (!Arrays.asList(TypeMap.get("image").split(",")).contains(  
  70.                     fileSuffix)) {  
  71.                 backInfo(response, false3"");  
  72.                 return;  
  73.             }  
  74.   
  75.             if (!ServletFileUpload.isMultipartContent(request)) {  
  76.                 backInfo(response, false, -1"");  
  77.                 return;  
  78.             }  
  79.   
  80.             // 检查上传文件的目录  
  81.             File uploadDir = new File(uploadPath);  
  82.             if (!uploadDir.isDirectory()) {  
  83.                 if (!uploadDir.mkdir()) {  
  84.                     backInfo(response, false4"");  
  85.                     return;  
  86.                 }  
  87.             }  
  88.   
  89.             // 是否有上传的权限  
  90.             if (!uploadDir.canWrite()) {  
  91.                 backInfo(response, false5"");  
  92.                 return;  
  93.             }  
  94.               
  95.             //新文件名  
  96.             String newname = "";  
  97.             if(null != filePre){  
  98.                 newname += filePre;//对应模块上传的文件名前缀  
  99.             }  
  100.               
  101.              newname += DateFormater.format(new Date(),  
  102.                     DateFormater.DATETIME_PATTERN) + "." + fileSuffix;  
  103.   
  104.             File saveFile = new File(uploadPath, newname);  
  105.   
  106.             try {  
  107.                 file.transferTo(saveFile);  
  108.                 backInfo(response, true0, newname);  
  109.             } catch (Exception e) {  
  110.                 LOG.error(e.getMessage(), e);  
  111.                 backInfo(response, false1"");  
  112.                 return;  
  113.             }  
  114.         } else {  
  115.             backInfo(response, false, -1"");  
  116.             return;  
  117.         }  
  118.   
  119.     }  
  120.   
  121.     // 返回信息  
  122.     private void backInfo(HttpServletResponse response, boolean flag, int message,  
  123.             String fileName) {  
  124.         String json  = "";  
  125.         if (flag) {  
  126.             json = "{ \"status\": \"success";   
  127.         } else {  
  128.             json = "{ \"status\": \"error";   
  129.         }  
  130.         json += "\",\"fileName\": \"" + fileName + "\",\"message\": \"" + message + "\"}";  
  131.         try {  
  132.             response.setContentType("text/html;charset=utf-8");  
  133.             response.getWriter().write(json);  
  134.         } catch (IOException e) {  
  135.             LOG.error(e.getMessage(), e);  
  136.         }  
  137.     }  
  138.   
  139. }  



 

 

         2、前台接受代码

          使用ajaxfileupload时,首先下载ajaxfileupload文件,导入对应的js文件

    

[html]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <script type="text/javascript" src="js/ajaxfileupload.js"></script>  

 

 

       文件传输字段必须为file类型,如下:

 

[html]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <input type="file" id="file" name="file" onchange="ajaxFileUpload();"/>  


      其次,处理上传文件:

 

           

[javascript]   view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.          //ajax 实现文件上传   
  2. unction ajaxFileUpload() {  
  3.   
  4. $.ajaxFileUpload({  
  5.     url : "upload/imageUpload.shtml",  
  6.     secureuri : false,  
  7.     data : {  
  8.         filePre : "feedback",  
  9.         p : new Date()  
  10.     },  
  11.     fileElementId : "file",  
  12.     dataType : "json",  
  13.     success : function(data) {  
  14.         if (data.status == "success") {  
  15.             //上传成功  
  16.         }  
  17.         switch(data.message){  
  18.          //解析上传状态  
  19.             case "0" : //上传成功  
  20.                        break;  
  21.             case "-1" : //上传文件不能为空  
  22.                       break;  
  23.             default//上传失败  
  24.                  break;  
  25.         }  
  26.     },  
  27.     error : function(data) {  
  28.         //上传失败  
  29.     }  
  30. });  


本文出处:http://blog.csdn.net/fengshizty

 

其实很简单。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值