前幾天在處理文件上傳的時候使用了下MultipartHttpServletRequest 覺得很好用,也非常方便,所以在這里記錄下,這里主要實現的是用戶使用Form方式上傳圖片,然后產生縮略圖,當然這里如
果有需要也可以把獲取到的Byte內容,存入公司或者自己的服務器里面,視需求而定哈。
比較常見的文件上傳組件有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。首先在
spring-mvc.xml配置文件中聲明一個MultipartResolver:
這樣一旦某個Request是一個MultipartRequest,它就會首先被MultipartResolver處理,然后再轉發相應的Controller。
在相關上傳文件接口中,將HttpServletRequest轉型為MultipartHttpServletRequest,就能非常方便地得到文件名和文件內容,然后可以將文件內容
轉為IO流進行存儲或顯示查看:
JavaCode部分:
1.獲取上傳詳細內容
2.生成縮略圖
- public static void createPreviewImage(String srcFile, String destFile) {
- try {
- File fi = new File(srcFile); // src
- File fo = new File(destFile); // dest
- BufferedImage bis = ImageIO.read(fi);
- int w = bis.getWidth();
- int h = bis.getHeight();
- double scale = (double) w / h;
- int nw = IMAGE_SIZE; // final int IMAGE_SIZE = 120;
- 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());
- }
- }
以上就是用戶在頁面通過Form方式提交文件上傳請求,然后MVC配置MultipartResolver攔截請求,使用MultipartHttpServletRequest將請求文件進行處理的相關步驟,非常的方便,寫在這里
留作筆記,MVC需要學習的東西還是有很多呀!!