【问题标题】:Flutter image upload to SpringBoot server not working颤振图像上传到 Spring Boot 服务器不起作用
【发布时间】: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 {
        }

我想提一下,如果我使用邮递员上传图片,该方法有效。我的颤振代码似乎有问题。

感谢您的帮助。

【问题讨论】:

  • @RequestPartrequired 的默认值为true,因此您不必提及并删除@RequestParam 而是执行此操作`@RequestPart("file")

标签: spring-boot flutter


【解决方案1】:

想通了。我没有使用new http.MultipartFile() 构造函数,而是使用了这个静态方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2019-05-09
    • 2017-06-11
    • 2015-02-23
    • 2020-04-29
    相关资源
    最近更新 更多