我凑了,捣鼓了这么久,我发现网上的教程是对的,主要是在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,因为参数对不上。