MultipartFile 文件上傳


1.文件必須選擇

@PostMapping("/UpLoad") 
public void UpLoad(@RequestParam MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{ if(!file.isEmpty()){ //上傳文件路徑 String path=""; File fileAllPath=new File(path); //上傳文件名 String fileName=file.getOriginalFilename(); File filePath=new File(path,fileName); //判斷是否存在,不存在新建 if(!filePath.getParentFile().exists()){ filePath.getParentFile().mkdir(); } //將文件放到一個文件目錄中去 file.transferTo(new File(path + File.separator + fileName)); } //參數獲取 request.getParameter("參數對應name"); }
 
         

 

 
        

 

2.文件自由選擇

 

@PostMapping("/UpLoad") 
public void UpLoad(HttpServletRequest request) throws IllegalStateException, IOException{ //判斷是否有文件需要上傳 String contentType = request.getContentType(); if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) { MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class); MultipartFile file = multipartRequest.getFile("file"); //file與傳遞過來的那么保持一致 } if(!file.isEmpty()){ //上傳文件路徑 String path=""; File fileAllPath=new File(path); //上傳文件名 String fileName=file.getOriginalFilename(); File filePath=new File(path,fileName); //判斷是否存在,不存在新建 if(!filePath.getParentFile().exists()){ filePath.getParentFile().mkdir(); } //將文件放到一個文件目錄中去 file.transferTo(new File(path + File.separator + fileName)); } //參數獲取 request.getParameter("參數對應name"); }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM