spring mvc 實現檔案上傳
html內容:
<input type="file" multiple="multiple" id="file_upload" name="file_upload" />
其中 multiple表示支援多檔案上傳
<button id='upload'>上傳</button>
//檔案上傳程式碼測試
$("#upload").click(function () {
var data=new FormData();//建立表單物件
data.append("pic",$("#file_upload")[0].files[0]);
data.append("fname","檔案");
$.ajax({
type: "post",
url: "http://localhost:1235/spring_mvc_test/uploadController/upload",
data: data,
contentType : false,
processData : false,
dataType: "json",
success: function(data){
alert("id:"+ data.result.userId +"pass:"+data.result.passWord);
}
});
服務端:
(這裡沒有選擇分層,所有邏輯都在controller裡實現的)
需要jar包 (commons-fileupload。jar commons-io.jar)
官方下載地址
http://commons.apache.org/proper/commons-fileupload/
http://commons.apache.org/proper/commons-io/
我用的
commons-fileupload-1.3.3.jar
commons-io-2.6.jar
配置檔案新增bean
<!-- 檔案上傳bean -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--每個檔案上傳大小-->
<property name="maxUploadSizePerFile" value="102400000"></property>
</bean>
@RequestMapping(value = "/uploadController/upload", method = RequestMethod.POST) @ResponseBody public Map<String, Object> upload(@RequestBody MultipartFile pic){ // 獲取檔案的名字 String oldName = pic.getOriginalFilename(); //獲得副檔名,並用UUID生成不重複的新檔名 String newName=UUID.randomUUID()+oldName.substring(oldName.lastIndexOf(".")); //上傳儲存伺服器的真是路徑 String realpath = "E:\\lee\\new"; String filename = pic.getOriginalFilename(); InputStream is = null; OutputStream os = null; String uuid = UUID.randomUUID().toString(); // 獲得檔案的字尾名 String endname = filename.substring(filename.lastIndexOf("."), filename.length()); // 通過spring 自帶工具包完成複製 try { is = pic.getInputStream(); os = new FileOutputStream(new File(realpath + "\\" + uuid + endname)); FileCopyUtils.copy(is, os); } catch (IOException e) { e.printStackTrace(); } finally { try { os.flush(); os.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } Map<String, Object> result = new HashMap<>(); result.put("message","上傳成功"); return result; }
注:如果上傳檔案亂碼,可以在配置bean裡新增屬性defaultEncoding" value="UTF-8"
完成