springMvc文件上傳,首先兩個基礎,前端
1.form表單屬性中加上enctype="multipart/form-data"spring
強調:form表單的<form method="post" ...,method必須有,我這裏是用的是post,至於get行不行沒試過,沒有method="post"也會報不是multipart請求的錯誤。後端
2.配置文件中配置MultipartResolverapp
文件超出限制會在進入controller前拋出異常,在容許範圍內這個配置無影響post
3.後端controller層參數接收測試
簡單的接收方法,思路:MultipartFile 接受文件並經過IO二進制流(MultipartFile.getInputStream())輸入到FileOutStream保存文件,而後該幹嗎就幹嗎編碼
參數接收同MultipartFile 接收同樣。spa
接受form表單截圖中name爲file和id的文件和參數。以下.net
@RequestMapping(value = "attendee_uploadExcel.do") @ResponseBody public void uploadExcel(@RequestParam("file") MultipartFile file, @RequestParam("id") String id) throws Exception { //form表單提交的參數測試爲String類型 if (file == null) return ; String fileName = file.getOriginalFilename(); String path = getRequest().getServletContext().getRealPath("/upload/excel"); //獲取指定文件或文件夾在工程中真實路徑,getRequest()這個方法是返回一個HttpServletRequest,封裝這個方法爲了處理編碼問題 FileOutputStream fos = FileUtils.openOutputStream(new File(path+"/" +fileName));//打開FileOutStrean流 IOUtils.copy(file.getInputStream(),fos);//將MultipartFile file轉成二進制流並輸入到FileOutStrean fos.close();// ...... }
2、先後端分享的文件上件方法,此時前端傳後後臺的爲文件base64編碼的字符串excel
其餘方法,將HttpServletRequest req強轉成MultipartHttpServletRequest req後,req.getParameter("id");
@ResponseBody @PostMapping("/import") public Integer importFromExcel(HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); // 經過參數名獲取指定文件 String id = multipartRequest.getParameter("id"); String fileName = file.getOriginalFilename(); ......... }
原文連接 http://blog.csdn.net/u013771277/article/details/47384817