天天看點

SSH架構之SpringMVC檔案上傳功能代碼

版權聲明:本文為部落客原創文章,如需轉載,請标明出處。 https://blog.csdn.net/alan_liuyue/article/details/79327717

簡介

  1.上一篇部落格我們講解了普遍情況下都适用的檔案上傳的功能代碼,那麼本篇部落格将會重點講解SSH架構之SpringMVC的檔案上傳代碼;

  2.SpringMVC架構本身就已經封裝了特有的檔案擷取和解析的方法,是以,我們之需要将這些方法熟練運用展示出即可;

  3.本篇執行個體将會分成四個步驟,給您展示一步到位的完善的springmvc檔案上傳:

  (1).需要的jar包;

  (2).jsp頁面;

  (3).xml配置;

  (4).背景controller處理方法;

執行個體

  1.需要提供的jar包:

commons.fileupload-1.2.1.jar; commons.io-1.4.0.jar

  

  2.jsp頁面:

<form action="uploadId" method="post" enctype="multipart/form-data">  
       <input type="file" name="idPic" />  
       <button >Submit</button>  
</form> 

<!--注意:要在form标簽中加上enctype="multipart/form-data"表示該表單是要處理檔案的,
這是最基本的東西,很多人會忘記然而當上傳出錯後則去找程式的錯誤,卻忘了這一點 -->           

  3.xml檔案配置:

<!-- SpringMVC上傳檔案時,需要配置MultipartResolver處理器 -->  
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8" />  
        <!-- 指定所上傳檔案的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個檔案,而是所有檔案的容量之和 -->  
        <property name="maxUploadSize" value="200000"/>  
        <property name="uploadTempDir" value="uploadTempDirectory" />
</bean>  

<!-- 屬性詳解:
defaultEncoding="UTF-8" 是請求的編碼格式,預設為iso-8859-1
maxUploadSize="200000" 是上傳檔案的大小,機關為位元組
uploadTempDir="uploadTempDirectory" 為上傳檔案的臨時路徑,可自定義  -->             

   4.背景controller處理方法類:

/**
 * springMVC檔案上傳方法執行個體
 * @author hqc
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/upload")
public class Uploadfile(){

    /** 
    * 單檔案上傳:
    * 用@RequestParam注解來指定表單上的file為MultipartFile  
    * 參數都會實行自動裝配~
    * @param multipartfile 
    * @return 
    * @throws IOException  
    */  
   @RequestMapping(value = "/uploadId")  
   @ResponseBody
   public String idIdentification(@RequestParam("idPic") MultipartFile multipartfile) throws IOException {  

       //測試擷取到的檔案資訊
       System.out.println("getOriginalFilename:"+multipartfile.getOriginalFilename());  
       System.out.println("getName:"+multipartfile.getName());  

       // 設定傳回的檔案格式,圖檔  
       //HttpHeaders headers = new HttpHeaders();  
       //headers.setContentType(MediaType.IMAGE_JPEG);  

       //擷取項目儲存檔案的根目錄
       String savePath = request.getSession().getServletContext().getRealPath("/uploadFile/placeImage");    

       //根據原檔案名使用時間戳和随機數重命名,儲存
       SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
       String fileName = imageFile.getOriginalFilename();
       String lastThreeLetter = fileName.substring(fileName.lastIndexOf("."));
       String sqlName = sdf.format(new Date())+(int)(Math.random()*10000)+lastThreeLetter;          

       //根據根目錄和檔案名,建立新的檔案路徑  
       File saveFile = new File(savePath+File.separator+sqlName);  

       //将擷取到的前台的檔案流轉換到新的檔案上面
       //springmvc已經封裝了輸入和輸出流方法,無需再寫輸入輸出流
       multipartfile.transferTo(saveFile);  

       //傳回json
        String json = "{\"result\":\""+result+"\"}";
        return json;

       //傳回頁面顯示使用者上傳的圖檔  
       //return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(saveFile), headers, HttpStatus.OK);  
   }  

    /** 
     * 多檔案上傳:
     * 前台可上傳多個檔案,使用MultipartFile的數組形式接收
     * @param multipartfiles 
     * @return 
     * @throws IllegalStateException 
     * @throws IOException 
     */  
    @RequestMapping(value = "/multiUploadId")  
    public String multiUpload(@RequestParam("idPic") MultipartFile[] multipartfiles)   
            throws IllegalStateException, IOException {  

        //擷取項目儲存檔案的根目錄
        String savePath = request.getSession().getServletContext().getRealPath("/uploadFile/placeImage"); 

        //格式化時間戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String timePath = sdf.format(new Date());

        if(null != multipartfiles && multipartfiles.length > 0){  
            //周遊并儲存檔案  
            for(MultipartFile file : multipartfiles){  
                //1. 使用原檔案名作為儲存的路徑
                //file.transferTo(new File(savePath + file.getOriginalFilename()));  

                //2. 針對每個檔案建立不同的時間戳+随機數名稱
                   String fileName = file.getOriginalFilename();
                   String lastThreeLetter = fileName.substring(fileName.lastIndexOf("."));
                   String sqlName = timePath+(int)(Math.random()*10000)+lastThreeLetter;    

                   //根據根目錄和檔案名,建立新的檔案路徑  
                   File saveFile = new File(savePath+File.separator+sqlName);

                   //将擷取到的每個檔案流分别轉換到新的檔案上面
                   //springmvc已經封裝了輸入和輸出流方法,無需再寫輸入輸出流
                   multipartfile.transferTo(saveFile);  
            }  
        }  
        return "redirect:uploadPage";  
    }  
}           

總結

  1.以上就是springMVC上傳檔案的全部流程,代碼也是簡潔友善,對于還不是很了解springmvc上傳檔案的程式猿還是有幫助的,有需要的可以自行複制代碼,然後可以經過自己的進一步加工,形成對自己最有效的一套代碼;

  2.實踐是檢驗認識真理的唯一标準,代碼好不好用,何不親自動手實踐看看;