我湊了,搗鼓了這麼久,我發現網上的教程是對的,主要是在ajax中添加兩句:
contentType: false, // 告訴jQuery不要去設置Content-Type請求頭,就不是默認的application/x-www-form-urlencoded了
processData: false, // 告訴jQuery不要去處理髮送的數據
我的錯誤在哪裏?我後端有設置接收參數@RequestParam(“myFile”),我以爲就是在data中設置對應的參數,可惜太晚發現了真相。
先給出代碼:
$('.UploadPicture-input').change(function () {
var fileData = this.files[0];
var formdata = new FormData();
formdata.append("myFile", fileData)
//注意這裏myFile是對應後端請求的參數名,否則提醒not a multipart
//而不是下面data設置的參數名data:{'':''},data直接提交整個form了
$.ajax({
type: "post",
url: "/upload",
data: formdata,
contentType: false, // 告訴jQuery不要去設置Content-Type請求頭,這樣就不是默認的application/x-www-form-urlencoded了
processData: false,// 告訴jQuery不要去處理髮送的數據
success: function (response) {
alert("成功!")
},
error: function () {
alert("失敗,沒有返回值,500")
}
});
有用mvc的話就配置個bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設置上傳文件的最大尺寸爲5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public WangEditor upload(@RequestParam("myFile") MultipartFile multipartFile, HttpServletRequest request) {
try {
// 獲取項目真實路徑,會包含工程目錄路徑,maven是獲取到out文件夾下的項目路徑
String realPath = request.getSession().getServletContext()
.getRealPath("");
System.out.println("realPath:" + realPath);
InputStream inputStream = multipartFile.getInputStream();
//獲得工程目錄路徑,也就是'/'後面的名稱,我這裏沒設置所以是空的
// String contextPath = request.getContextPath();
// System.out.println("contextPath:" + contextPath);
//真實路徑去掉後面的工程路徑
// String path = realPath.replace(contextPath.substring(1), "");
// System.out.println("path:" + path);
// 根目錄下新建文件夾upload,存放上傳圖片,前端想要資源就直接訪問localhost:8080/upload/...
String uploadPath = realPath + "upload"; //結果應該是'項目路徑/upload'
// 設置隨機文件名稱
String filename = Calendar.getInstance().getTimeInMillis() + "image.jpg";
System.out.println("filename:" + filename);
// 拼接好路徑和圖片名稱後創建具體文件,下面就是讀取從前端獲取到的文件數據然後輸出到具體文件中應該就這樣
File file = new File(uploadPath, filename);
FileUtils.copyInputStreamToFile(inputStream, file);
// 拼接圖片的訪問路徑,就http://localhost:8080/upload/....jpg
String url = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + "/upload/" + filename;
System.out.println("url:" + url);
//這裏開始就是自己設置的接口格式了,我是使用了編輯器wangeditor3所以參考的返回格式
String[] strs = {url};
WangEditor we = new WangEditor(strs);
return we;
} catch (IOException e) {
System.out.println("文件上傳失敗");
}
return null;
}
全部重點就在ajax中,誤以爲data{}中設置請求參數,但其實data對應的是整個form,而form其中的multipart纔是具體參數該對應的,因爲form可以放多個part。我湊了,搞了我這麼久,哎。感謝網上大神的指點!
對了,the request was rejected because no multipart boundary was found 應該也是這個問題,沒找到part,因爲參數對不上。