java Spring MVC解析多部分内容请求
我将继续学习本教程https://spring.io/guides/gs/uploading-files/ 并实现了一个多部分文件上传控制器
然而,我一直无法理解这个错误:
type Exception report
message Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
description The server encountered an internal error that prevented it from fulfilling this request.
这是我的控制器的代码,就在官方教程中:
package com.springapp.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
@Controller
public class FileUploadController {
@RequestMapping(value="/api/items/upload_image", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + "!";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
}
为了获得更多信息,我在angularjs上通过前端发送请求。请求senging成功:
Upload.upload({
url: '/api/items/upload_image',
file: $file,
name: $file.name,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
我认为问题可能是什么? 包括所有需要的依赖项
# 1 楼答案
这是一个解决方案: 在pom中包含此依赖项。xml
在配置中添加此bean: