1. 程式人生 > >Spring中MultipartHttpServletRequest實現檔案上傳

Spring中MultipartHttpServletRequest實現檔案上傳

實現圖片上傳 
  使用者必須能夠上傳圖片,因此需要檔案上傳的功能。比較常見的檔案上傳元件有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 程式碼
  1. <bean id="multipartResolver"  
  2.     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  3.     <!-- 設定上傳檔案的最大尺寸為1MB -->  
  4.     <property name="maxUploadSize">  
  5.         <value>1048576</value>  
  6.     </property>  
  7. </bean>  

 這樣一旦某個Request是一個MultipartRequest,它就會首先被MultipartResolver處理,然後再轉發相應的Controller。 
在UploadImageController中,將HttpServletRequest轉型為MultipartHttpServletRequest,就能非常方便地得到檔名和檔案內容:

java 程式碼
  1. public ModelAndView handleRequest(HttpServletRequest request,   
  2.             HttpServletResponse response) throws Exception {   
  3.         // 轉型為MultipartHttpRequest:   
  4.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
  5.         // 獲得檔案:   
  6.         MultipartFile file = multipartRequest.getFile(" file "
    );   
  7.         // 獲得檔名:   
  8.         String filename = file.getOriginalFilename();   
  9.         // 獲得輸入流:   
  10.         InputStream input = file.getInputStream();   
  11.         // 寫入檔案   
  12.         // 或者:   
  13.         File source = new File(localfileName.toString());   
  14.         multipartFile.transferTo(source);   
  15.     }  

生成縮圖 (目錄)
  當用戶上傳了圖片後,必須生成縮圖以便使用者能快速瀏覽。我們不需藉助第三方軟體,JDK標準庫就包含了影象處理的API。我們把一張圖片按比例縮放到120X120大小,以下是關鍵程式碼:

java 程式碼
  1. public static void createPreviewImage(String srcFile, String destFile) {   
  2.         try {   
  3.             File fi = new File(srcFile); // src   
  4.             File fo = new File(destFile); // dest   
  5.             BufferedImage bis = ImageIO.read(fi);   
  6.             int w = bis.getWidth();   
  7.             int h = bis.getHeight();   
  8.             double scale = (double) w / h;   
  9.             int nw = IMAGE_SIZE; // final int IMAGE_SIZE = 120;   
  10.             int nh = (nw * h) / w;   
  11.             if (nh > 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.     }  

相關推薦

SpringMultipartHttpServletRequest實現檔案

實現圖片上傳    使用者必須能夠上傳圖片,因此需要檔案上傳的功能。比較常見的檔案上傳元件有Commons FileUpload(http://jakarta.apache.org/commons/fileupload/a>)和COS FileUpload(http

common-fileUpload和 SpringMultipartHttpServletRequest實現檔案、以及過濾器的問題

遇到一個專案中寫的過濾器有些不明白為什麼那麼寫,其實就是以下的第二部分不理解造成的 二、 使用servlet時:多部件表單上傳對servlet取值問題 1)  request.getParameter("..."),這個方法在表單為multiparty/form-d

基於tobato的fastdfs與spring boot整合實現檔案和下載

專案結構: pom.xml檔案新增配置: <!-- fastdfs --> <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastd

flask如何實現檔案

首先請看templates中的html模板 特別要注意,模板中必須要使用 enctype="multipart/form-data" , 否則form不會做任何事情 <!DOCTYPE html

如何用spring整合mongodb實現檔案

首先要把必要的mongoDB需要的jar加進專案中 定義mongoDB的bean <bean id="mongoClient" class="com.mongodb.MongoClient"> <constructor-arg index="

Spring Mvc poi實現檔案

    上傳檔案有很多種方法,這裡主要講通過poi元件(jar包))實現檔案上傳。專案依賴commons-io.jar和commons-fileupload(版本沒有太大要求,能實現功能即可),樓主用的是commons-fileupload-1.3.1.jar和commons

Java Servlet實現檔案並讀取Zip壓縮包檔案的真實型別

1.上傳檔案servlet PS: 使用ant.jar中的 org.apache.tools.zip.ZipEntry 物件,防止亂碼 package com.chenl.servlets; import java.io.File; import java.io.IOExcep

React使用fetch實現檔案下載

在最近的專案中需要實現檔案上傳下載功能,在以前spring、jsp的專案中實現檔案上傳很簡單,但現在前後端分離,前端使用React,後端使用Spring Boot,實現就沒那麼方便了。 前端React使用fetch而非傳統的XMLHttpRequest從後端獲取

Java利用MultipartFile實現檔案

JavaWeb專案頁面實現檔案上傳功能 jsp檔案增加檔案上傳控制元件,可以放在form表單內,增加隱藏域儲存上傳路徑提交到後臺。 <div class="form-group"> <div class="col-sm-7 center "&g

怎麼簡便地去掉html難看的檔案按鈕並實現圖片預覽功能?

問題描述 通常的檔案上傳按鈕是這樣的: 選擇了檔案過後是這樣的: 很顯然,這樣的按鈕並不好看。 解決方法 用一個label標籤來裝載樣式,其for屬性指向type=file的inp

PHP程式碼是如何實現檔案的?

這裡使用PHP的全域性陣列$_FILES來實現檔案上傳: $_FILES[“file”][“name”] - 被上傳檔案的名稱 $_FILES[“file”][“type”] - 被上傳檔案的型別 $_FILES[“file”][“size”] - 被上傳檔案的大小,以位元組計 $_F

spring mvc 實現檔案

html內容:<input type="file" multiple="multiple" id="file_upload" name="file_upload" /> 其中 multiple表示支援多檔案上傳<button id='upload'>上

Java實現檔案下載的三種解決方案

第一點:Java程式碼實現檔案上傳   FormFile file=manform.getFile();    String newfileName = null;   String newpathname=null;   String fileAddre="/numU

Spring Boot實現檔案

一、檔案上傳的配置 Spring Boot預設支援檔案上傳,對檔案上傳支援友好。對上傳進行配置如下: # 配置上傳引數 spring: http: multipart: enabled: true # 預設

spring實現檔案和下載 完整方案

1. 簡介 提供基於spring實現檔案(筆記附件)的上傳和下載的完整方案。方案將檔案上傳,並將檔名稱作為欄位與關聯的筆記繫結在一起,更新筆記在資料庫中的記錄。顯示筆記時,根據筆記所繫結的檔名生成下載

python+selenium win32gui實現檔案 enumerate() Unity3dSendMessage 用法簡單筆記

upload = dr.find_element_by_id('exampleInputFile0') upload.click() time.sleep(1) # win32gui dialog = win32gui.FindWindow('#32770', u'開啟') # 對話方塊 ComboBoxE

框架如何根據fileupload工具包實現檔案功能

工具包 Apache-fileupload.jar – 檔案上傳核心包。 Apache-commons-io.jar – 這個包是fileupload的依賴包。同時又是一個工具包。 程式碼  servletFileUpload官方API /*獲取tomcat的wor

spring springmvc實現檔案

1.建立web專案fileDemo web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

spring boot實現檔案下載以及多檔案

首先是很簡單的介面,在resource/static下建立檔案file.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymel