Flutter Image上传到Springboot服务器不起作用



我正在尝试使用以下代码从我的扑波应用程序上载图像:

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 {
        }

我想提到,如果我使用邮递员上传图像,则该方法有效。我的flutter代码似乎有问题。

感谢您的任何帮助。

弄清楚了。而不是使用new http.MultipartFile()构造函数,我使用了此静态方法:

request.files.add(await http.MultipartFile.fromPath('file', image.path,
    contentType: new MediaType('image', imageType)));

最新更新