轉貼自:http://zhupan.iteye.com/blog/26427
實現圖片上傳
用戶必須能夠上傳圖片,因此需要文件上傳的功能。比較常見的文件上傳組件有Commons FileUpload(http://jakarta.apache.org/commons/fileupload/a>)和COS FileUpload(http://www.servlets.com/cos),Spring已經完全集成了這兩種組件,這里我們選擇Commons FileUpload。
由于Post一個包含文件上傳的Form會以multipart/form-data請求發送給服務器,必須明確告訴DispatcherServlet如何處理MultipartRequest。首先在dispatcher-servlet.xml中聲明一個MultipartResolver:
xml 代碼
- <bean?id="multipartResolver"??
- ????class="org.springframework.web.multipart.commons.CommonsMultipartResolver">??
- ??????
- ????<property?name="maxUploadSize">??
- ????????<value>1048576</value>??
- ????</property>??
- </bean>??
?這樣一旦某個Request是一個MultipartRequest,它就會首先被MultipartResolver處理,然后再轉發相應的Controller。
在UploadImageController中,將HttpServletRequest轉型為MultipartHttpServletRequest,就能非常方便地得到文件名和文件內容:
java 代碼
- public?ModelAndView?handleRequest(HttpServletRequest?request, ??
- ????????????HttpServletResponse?response)?throws?Exception?{ ??
- ??????????
- ????????MultipartHttpServletRequest?multipartRequest?=?(MultipartHttpServletRequest)?request; ??
- ??????????
- ????????MultipartFile?file?=?multipartRequest.getFile("?file?"); ??
- ??????????
- ????????String?filename?=?file.getOriginalFilename(); ??
- ??????????
- ????????InputStream?input?=?file.getInputStream(); ??
- ??????????
- ??
- ??????????
- ????????File?source?=?new?File(localfileName.toString()); ??
- ????????multipartFile.transferTo(source); ??
- ????}??
生成縮略圖 (目錄)
當用戶上傳了圖片后,必須生成縮略圖以便用戶能快速瀏覽。我們不需借助第三方軟件,JDK標準庫就包含了圖像處理的API。我們把一張圖片按比例縮放到120X120大小,以下是關鍵代碼:
java 代碼
- public?static?void?createPreviewImage(String?srcFile,?String?destFile)?{ ??
- ????????try?{ ??
- ????????????File?fi?=?new?File(srcFile);???
- ????????????File?fo?=?new?File(destFile);???
- ????????????BufferedImage?bis?=?ImageIO.read(fi); ??
- ??
- ????????????int?w?=?bis.getWidth(); ??
- ????????????int?h?=?bis.getHeight(); ??
- ????????????double?scale?=?(double)?w?/?h; ??
- ????????????int?nw?=?IMAGE_SIZE;???
- ????????????int?nh?=?(nw?*?h)?/?w; ??
- ????????????if?(nh?>?IMAGE_SIZE)?{ ??
- ????????????????nh?=?IMAGE_SIZE; ??
- ????????????????nw?=?(nh?*?w)?/?h; ??
- ????????????} ??
- ????????????double?sx?=?(double)?nw?/?w; ??
- ????????????double?sy?=?(double)?nh?/?h; ??
- ??
- ????????????transform.setToScale(sx,?sy); ??
- ????????????AffineTransformOp?ato?=?new?AffineTransformOp(transform,?null); ??
- ????????????BufferedImage?bid?=?new?BufferedImage(nw,?nh, ??
- ????????????????????BufferedImage.TYPE_3BYTE_BGR); ??
- ????????????ato.filter(bis,?bid); ??
- ????????????ImageIO.write(bid,?"?jpeg?",?fo); ??
- ????????}?catch?(Exception?e)?{ ??
- ????????????e.printStackTrace(); ??
- ????????????throw?new?RuntimeException( ??
- ????????????????????"?Failed?in?create?preview?image.?Error:??"??
- ????????????????????????????+?e.getMessage()); ??
- ????????} ??
- ????}??