---
title: "Spring中实现文件上传"
author: "grefr"
date: "2014-07-13T13:02:05Z"
tags: []
categories: ["开源软件"]
slug: "spring"
draft: false
lastmod: "2015-06-24T14:05:07Z"
id: 2091555
url: "https://grefr.iteye.com/blog/2091555"
---

详见： [http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt110](http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt110)

 

实现图片上传   
　　用户必须能够上传图片，因此需要文件上传的功能。比较常见的文件上传组件有Commons FileUpload（[http://jakarta.apache.org/commons/fileupload/a](http://jakarta.apache.org/commons/fileupload/a)&gt;）和COS FileUpload（[http://www.servlets.com/cos](http://www.servlets.com/cos)），Spring已经完全集成了这两种组件，这里我们选择Commons FileUpload。   
　　由于Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器，必须明确告诉DispatcherServlet如何处理MultipartRequest。首先在dispatcher-servlet.xml中声明一个MultipartResolver：

xml 代码

1. &lt;bean id="multipartResolver"
2. class="org.springframework.web.multipart.commons.CommonsMultipartResolver"&gt;
3. &lt;!-- 设置上传文件的最大尺寸为1MB --&gt;
4. &lt;property name="maxUploadSize"&gt;
5. &lt;value&gt;1048576&lt;/value&gt;
6. &lt;/property&gt;
7. &lt;/bean&gt;

 这样一旦某个Request是一个MultipartRequest，它就会首先被MultipartResolver处理，然后再转发相应的Controller。   
在UploadImageController中，将HttpServletRequest转型为MultipartHttpServletRequest，就能非常方便地得到文件名和文件内容：

java 代码

01. public ModelAndView handleRequest(HttpServletRequest request,
02. HttpServletResponse response) throws Exception {
03. // 转型为MultipartHttpRequest：
04. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
05. // 获得文件：
06. MultipartFile file = multipartRequest.getFile(" file ");
07. // 获得文件名：
08. String filename = file.getOriginalFilename();
09. // 获得输入流：
10. InputStream input = file.getInputStream();
11. // 写入文件
12. // 或者：
13. File source = new File(localfileName.toString());
14. multipartFile.transferTo(source);
15. }

生成缩略图 (目录)  
　　当用户上传了图片后，必须生成缩略图以便用户能快速浏览。我们不需借助第三方软件，JDK标准库就包含了图像处理的API。我们把一张图片按比例缩放到120X120大小，以下是关键代码：

java 代码

01. public static void createPreviewImage(String srcFile, String destFile) {
02. try {
03. File fi = new File(srcFile); // src
04. File fo = new File(destFile); // dest
05. BufferedImage bis = ImageIO.read(fi);
06. int w = bis.getWidth();
07. int h = bis.getHeight();
08. double scale = (double) w / h;
09. int nw = IMAGE\_SIZE; // final int IMAGE\_SIZE = 120;
10. int nh = (nw * h) / w;
11. if (nh &gt; IMAGE\_SIZE) {
12. nh = IMAGE\_SIZE;
13. nw = (nh * w) / h;
14. }
15. double sx = (double) nw / w;
16. double sy = (double) nh / h;
17. transform.setToScale(sx, sy);
18. AffineTransformOp ato = new AffineTransformOp(transform, null);
19. BufferedImage bid = new BufferedImage(nw, nh,
20. BufferedImage.TYPE\_3BYTE\_BGR);
21. ato.filter(bis, bid);
22. ImageIO.write(bid, " jpeg ", fo);
23. } catch (Exception e) {
24. e.printStackTrace();
25. throw new RuntimeException(
26. " Failed in create preview image. Error:  "
27. + e.getMessage());
28. }
29. }