SpringMVC实现文件上传&下载(2)

打印 上一主题 下一主题

主题 898|帖子 898|积分 2694

文件上传步骤

第一步:由于SpringMVC利用的是commons-fileupload实现,故将其组件引入项目中,这里用到的是commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。
第二步:spring-mvx中配置MultipartResolver处理器。可在此加入对上传文件的属性限制。
第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容
第四步:编写前台表单。注意enctype="multipart/form-data"以及,如果是单个文件直接利用MultipartFile 即可
springmvc.xml
  1. <bean id="multipartResolver"  
  2.    >
  3.      
  4.    <property name="maxUploadSize">  
  5.        <value>10000000</value>  
  6.    </property>  
  7.   </bean>  
复制代码
controller
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import org.apache.commons.fileupload.FileUpload;
  9. import org.apache.commons.io.FileUtils;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestParam;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import org.springframework.web.servlet.ModelAndView;
  15. @Controller
  16. public class FileUploadController {
  17.     //TODO:上传代码
  18.     @RequestMapping("/fileupload")
  19.     public ModelAndView upload(String name,
  20.             //上传多个文件
  21.             @RequestParam("file") MultipartFile[] file,
  22.             HttpServletRequest request) throws IllegalStateException,
  23.             IOException {
  24.         //获取文件 存储位置
  25.         String realPath = request.getSession().getServletContext()
  26.                 .getRealPath("/uploadFile");
  27.         File pathFile = new File(realPath);
  28.         if (!pathFile.exists()) {
  29.             //文件夹不存 创建文件
  30.             pathFile.mkdirs();
  31.         }
  32.         for (MultipartFile f : file) {
  33.             System.out.println("文件类型:"+f.getContentType());
  34.             System.out.println("文件名称:"+f.getOriginalFilename());
  35.             System.out.println("文件大小:"+f.getSize());
  36.             System.out.println(".................................................");
  37.             //将文件copy上传到服务器
  38.             f.transferTo(new File(realPath + "/" + f.getOriginalFilename()));
  39.              //FileUtils.copy
  40.         }
  41.         //获取modelandview对象
  42.         ModelAndView view = new ModelAndView();
  43.         view.setViewName("redirect:index.jsp");
  44.         return view;
  45.     }
  46.     //TODO:下载代码
  47.     @RequestMapping(value = "/filedownload")  
  48.     public ModelAndView download(HttpServletRequest request,  
  49.             HttpServletResponse response) throws Exception {  
  50. //        String storeName = "Spring3.xAPI_zh.chm";  
  51.         String storeName="文件.txt";
  52.         String contentType = "application/octet-stream";  
  53.         FileUploadController.download(request, response, storeName, contentType);  
  54.         return null;  
  55.     }  
  56.     //文件下载 主要方法
  57.     public static void download(HttpServletRequest request,  
  58.             HttpServletResponse response, String storeName, String contentType
  59.            ) throws Exception {  
  60.         request.setCharacterEncoding("UTF-8");  
  61.         BufferedInputStream bis = null;  
  62.         BufferedOutputStream bos = null;  
  63.         //获取项目根目录
  64.         String ctxPath = request.getSession().getServletContext()  
  65.                 .getRealPath("");  
  66.         //获取下载文件露肩
  67.         String downLoadPath = ctxPath+"/uploadFile/"+ storeName;  
  68.         //获取文件的长度
  69.         long fileLength = new File(downLoadPath).length();  
  70.         //设置文件输出类型
  71.         response.setContentType("application/octet-stream");  
  72.         response.setHeader("Content-disposition", "attachment; filename="  
  73.                 + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
  74.         //设置输出长度
  75.         response.setHeader("Content-Length", String.valueOf(fileLength));  
  76.         //获取输入流
  77.         bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
  78.         //输出流
  79.         bos = new BufferedOutputStream(response.getOutputStream());  
  80.         byte[] buff = new byte[2048];  
  81.         int bytesRead;  
  82.         while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  83.             bos.write(buff, 0, bytesRead);  
  84.         }  
  85.         //关闭流
  86.         bis.close();  
  87.         bos.close();  
  88.     }  
  89. }  
复制代码
注意:注意:设置表单中form表单的属性为:enctype="multipart/form-data"

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

河曲智叟

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表