【发布时间】:2019-11-18 12:55:15
【问题描述】:
我正在尝试使用以下代码从我的 Flutter 应用程序上传图像:
Future<String> saveImage(File image) async {
var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
String token = "blah"; //token for authentication
var uri = Uri.parse(url); //I get the URL from some config
Map<String, String> headers = { "Authorization": "Bearer $token", "content-type": "multipart/form-data" };
var request = new http.MultipartRequest("POST", uri);
request.headers.addAll(headers);
var multipartFile = new http.MultipartFile('file', stream, length);
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
但是这个请求在我的 spring-boot 服务器上失败并出现以下错误:
{"timestamp":1562637369179,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/api/v1/user/photo"}
这就是我的 Java 控制器方法的样子:
@RequestMapping(value = "/photo", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadImage(@RequestPart(required = true) @RequestParam("file") MultipartFile image) throws IOException {
}
我想提一下,如果我使用邮递员上传图片,该方法有效。我的颤振代码似乎有问题。
感谢您的帮助。
【问题讨论】:
-
在
@RequestPart中required的默认值为true,因此您不必提及并删除@RequestParam而是执行此操作`@RequestPart("file")
标签: spring-boot flutter