注意:
- form表單提交input的type=file時,form的enctype="multipart/form-data",才能提交file的文件流到後臺
- 必須用FormData對象存儲和提交表單中的值
- FormData的append方法存儲表單數據
下面以上傳圖片爲例:
HTML代碼:
<form action="" method="post" id="addProduct">
產品圖片:<input type="file" name="file" id="file"/>
<input type="button" value="添加" id="add_button"/>
</form>
JS代碼:
var url = document.getElementById("file").value; //獲取圖片名字
var hasFile = url === ""; //判斷是否選中圖片
console.log(hasFile);
url = url.split("."); //獲取圖片後綴名
image_url = "圖片" + "." + url[url.length - 1]; //重新生成圖片名
upImage(image_url);
function upImage(image_url) {
var formData = new FormData($("#addProduct")[0]); //獲取表單的圖片數據
// console.log($('#file')[0]);
// formData.append("file", $('#file')[0]);
//
formData.append("fileName", image_url);
$.ajax({
type: "post",
url: "/cv/private/upimage", //接受處理的url
async: true,
data: formData,
processData: false, //必須false纔會避開jQuery對 formdata 的默認處理
contentType: false, //必須false纔會自動加上正確的Content-Type
success: function (data) {
console.log(data);
}
});
java代碼:
//成功返回1
@RequestMapping("/upimage")
public void upImage(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException {
int num;
if (!file.isEmpty()) {
//System.out.println(1);
String dirPath = request.getSession().getServletContext().getRealPath("/") + "/upImage";
File filePath = new File(dirPath);
System.out.println(filePath.getAbsolutePath());
if (!filePath.exists()) {
//System.out.println(2);
response.getWriter().print("{\"num\":" + 0 + "}");
return;
}
try {
//System.out.println(3);
file.transferTo(new File(dirPath + "/" + fileName));
num = 1;
response.getWriter().print("{\"num\":" + num + "}");
} catch (Exception e) {
e.printStackTrace();
//System.out.println(4);
response.getWriter().print("{\"num\":" + 0 + "}");
}
}//end if
else {
response.getWriter().print("{\"num\":" + 0 + "}");
}
}
參考: