script>
function uploadfile(){
$.ajax({
url : "/url/upload",
data: new FormData($("#form-avatar")[0]),
type : "POST",
// 告訴jQuery不要去處理發送的數據,用于對data參數進行序列化處理 這里必須false
processData : false,
// 告訴jQuery不要去設置Content-Type請求頭
contentType : false,
success : function(json) {
alert("執行成功");
},
error : function(json) {
alert("執行失敗");
}
});
}
$("#btn-avatar").on("click",uploadfile);
/script>
@PostMapping("/upload")
public void fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
System.out.println("走了");
//上傳路徑保存設置
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()));
}