【问题标题】:Flutter http 400 error when sending an XFile Image发送 XFile 图像时出现 Flutter http 400 错误
【发布时间】:2022-11-22 16:14:19
【问题描述】:

我想将一个 jpg 文件从我的 flutter 应用程序发送到 .Net 后端。我正在使用 http 包。

我的代码如下:

var uri = Uri.parse('$url/upload/$id');
var request = http.MultipartRequest('POST', uri);

var headers = {'accept': '*/*', 'Content-Type': 'multipart/form-data'};

request.headers.addAll(headers);

var x = await file.readAsBytes();
var mFile = http.MultipartFile.fromBytes('file', x);
request.files.add(mFile);

var response = await request.send();

这里file 是包cross_file 中的一个XFile 文件。

不幸的是,我收到错误代码 - 400“错误请求”。

在后端代码如下所示

 [HttpPost("/upload/{id}")]
 public IActionResult UploadImage(IFormFile imageFormFile, [FromRoute] Guid id)
 {
     // program does not even enter the function
 }

我已经使用 Swagger 对此进行了测试并且它有效,它会生成以下卷曲:

    curl -X 'POST' \
  'http://localhost:44383/apiname/f7765448-be93-4e72-b62e-04623b4ccdb1' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F 'imageFormFile=@sample.jpg;type=image/jpeg'

我搜索了一些论坛和教程,但没有任何效果。

我试过使用fromBytesfromPathfromString 添加文件,但均无效。

我试过尝试不同的标题和字段组合,这也没有用。特别是我尝试添加字段“imageFormFile”和“type”,就像在 Swagger curl 中一样,但效果不佳。

我也尝试使用 dio 重写它,但得到了相同的结果(而且我宁愿坚持使用 http,因为我的项目的其余部分使用它)。

【问题讨论】:

    标签: flutter image api rest file-upload


    【解决方案1】:
    Future uploadRequest(String url, String filePath) async {
       final dio = Dio();
       dio.options.contentType = "multipart/form-data";
       final multiPartFile = await MultipartFile.fromFile(
         filePath,
         filename: filePath.split('/').last,
       );
       FormData formData = FormData.fromMap({
         "file": multiPartFile,
       });
       final response = await dio.post(
         url,
         data: formData,
       );
       return response.data;
    }
    

    这是 100% 有效的解决方案,但带有 dio 包,因为我更喜欢它而不是 http。但这并不意味着使用 http 是不可能的。

    重要的: 表单数据根据您的 API 可能会有所不同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2014-08-22
      • 2018-02-01
      • 2020-03-30
      • 2016-01-06
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多