SpringMVC的上傳和下載


文件上傳:

一:單文件上傳java

  步驟以下:web

  1.導入jar包spring

   

  2.書寫控制器方法 獲取到文件路徑apache

  

  3.applicationContext大配置:app

  

  4.繪製頁面,進行渲染webapp

  

  假如說如今測試項目的話,會出現一個問題:(500錯誤信息:沒法實例化MultipartFile)post

  

  解決方案:測試

  在大配置進行註解驅動的配置:spa

  

  

  咱們進行單個文件上傳後,會感受不太嚴謹,想再規範限定一下它的文件類型,因而作了下面這個操做:3d

  經過後綴名控制文件上傳的類型:

  

  進行一個判斷,限定一下,還想到,假如說沒有進行文件的上傳,可是用戶點擊了上傳按鈕,會讓他進入上傳頁面:

  

二:多文件上傳

  


文件下載:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class MyController {

	@RequestMapping("download.do")    
    public ResponseEntity<byte[]> download() throws IOException {    
        File file=new File("F:\\Y2\\OA\\.metadata\\.me_tcat\\webapps\\SpringMVC_fileupload\\images\\111.jpg");  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String("你好.jpg".getBytes("utf-8"),"iso-8859-1");//爲了解決中文名稱亂碼問題  
        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }    
	
}
<form action="${pageContext.request.contextPath}/frist.do" method="post" enctype="multipart/form-data">
 			文件:<input type="file" name="uploadFile"/><br/>
 			    <input type="submit" value="上傳"/>
 	</form> 
 	
 	<a href="${pageContext.request.contextPath}/download.do?111.jpg">下載</a>
 	
 	註解版配置歡迎你的使用~~~

相關文章
相關標籤/搜索