1. 程式人生 > 其它 >SpringMVC檔案上傳和下載(基本步驟)

SpringMVC檔案上傳和下載(基本步驟)

技術標籤:學習筆記狂神springmvc

檔案上傳

  1. 引入jar包
    <dependency>
    	 <groupId>commons-fileupload</groupId> 
     	<artifactId>commons-fileupload</artifactId> 
     	<version>1.3.3</version> 
    </dependency>
    
  2. 配置bean:multipartResolver
    【注意!!!這個bena的id必須為:multipartResolver , 否則上傳檔案會報400的錯誤!】
    <!--檔案上傳配置-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolve r"> <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容, 預設為ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- 上傳檔案大小上限,單位為位元組(10485760=10M) -->
    <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
  3. Controller
    	/** 採用file.Transto 來儲存上傳的檔案 */ 
    	@RequestMapping("/upload2") 
    	public String fileUpload2(@RequestParam("file"
    ) CommonsMultipartFile file, HttpServletRequest request) throws IOException { //上傳路徑儲存設定 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上傳檔案地址 System.out.println("上傳檔案儲存地址:"+realPath); //通過CommonsMultipartFile的方法直接寫檔案(注意這個時候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; }

檔案下載

檔案下載步驟:

  1. 設定 response 響應頭

  2. 讀取檔案 – InputStream

  3. 寫出檔案 – OutputStream

  4. 執行操作

  5. 關閉流 (先開後關)

    @RequestMapping(value="/download") 
    public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{ 
    	//要下載的圖片地址 
    	String path = request.getServletContext().getRealPath("/upload"); 
    	String fileName = "基礎語法.jpg";
    	//1、設定response 響應頭 
    	response.reset(); 
    	//設定頁面不快取,清空buffer 
    	response.setCharacterEncoding("UTF-8"); 
    	//字元編碼 
    	response.setContentType("multipart/form-data"); 
    	//二進位制傳輸資料 
    	//設定響應頭 
    	response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8")); 
    	File file = new File(path,fileName); 
    	//2、 讀取檔案--輸入流 
    	InputStream input=new FileInputStream(file); 
    	//3、 寫出檔案--輸出流 
    	OutputStream out = response.getOutputStream();
    	byte[] buff =new byte[1024];
    	int index=0; 
    	//4、執行 寫出操作 
    	while((index= input.read(buff))!= -1){ 
    		out.write(buff, 0, index); 
    		out.flush(); 
    	}
    	out.close(); 
    	input.close(); 
    	return null; 
    }