如何在flutter和dart中发送多部分表单数据?

ukxgm1gy  于 2023-03-09  发布在  Flutter
关注(0)|答案(1)|浏览(152)

我尝试在Flutter中发送一个多部分表单。我查看了示例代码,在网络跟踪中看到了除多部分文件之外的所有字段。以下是我的代码:

final request = http.MultipartRequest('POST', Uri.parse(Env.flowServer));

  // add the text form fields
  final headers = request.headers;
  headers['Cookie'] = Login.cookieHeader;
  final formFields = request.fields;
  formFields['jobId'] = chunk.jobId.toString();
  formFields['flowChunkNumber'] = chunk.flowChunkNumber.toString();
  formFields['flowChunkSize'] = chunk.flowChunkSize.toString();
  formFields['flowCurrentChunkSize'] = chunk.flowCurrentChunkSize.toString();
  formFields['flowTotalSize'] = chunk.flowTotalSize.toString();
  formFields['flowIdentifier'] = chunk.flowIdentifier;
  formFields['flowFilename'] = chunk.flowFilename;
  formFields['flowRelativePath'] = chunk.flowRelativePath;
  formFields['flowTotalChunks'] = chunk.flowTotalChunks.toString();
  formFields['notesByFileName'] = chunk.notesByFileName;

  // add the data
  final formFiles = request.files;
  formFiles.add(http.MultipartFile.fromBytes('file', chunk.file));
  final response = await request.send();

我得到一个状态代码400-bad request。我将Flutter应用作为Chrome网络应用运行,这样我就可以做网络跟踪。我看到数据被发布,但它缺少"文件"字段。
下面是网络跟踪显示的内容:

POST /handlers/images/flow.php HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 62350
Host: staging.ocgmegamax.com
Origin: http://localhost:64983
Referer: http://localhost:64983/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36
content-type: multipart/form-data; boundary=dart-http-boundary-sFZv4IvT.au3x5Ut1IZI11mjRFwPPiHi4CNiJQLDEj6Wjgaz0Op

the form fields:
jobId: 148951
flowChunkNumber: 1
flowChunkSize: 65536
flowCurrentChunkSize: 60588
flowTotalSize: 60588
flowIdentifier: 60588-sample_upload_photo_smalljpeg
flowFilename: sample_upload_photo_small.jpeg
flowRelativePath: sample_upload_photo_small.jpeg
flowTotalChunks: 1
notesByFileName: {"60588-sample_upload_photo_smalljpeg":"This is a low-res photo of a flower"}

数据对于我正在调用的服务是正确的。当我运行一个真正的Web应用成功调用此服务时,它会传递类似的数据,但我也会看到文件字段。以下是一个示例:

jobId: 150190
flowChunkNumber: 1
flowChunkSize: 262144
flowCurrentChunkSize: 262144
flowTotalSize: 1074223
flowIdentifier: 1074223-mansion_housejpeg
flowFilename: mansion_house.jpeg
flowRelativePath: mansion_house.jpeg
flowTotalChunks: 4
file: (binary)
notesByFileName: {"1074223-mansion_housejpeg":"test"}

我传递给MultipartFile的数据是一个大约60,000字节的List。
任何帮助都将不胜感激。

nhhxz33t

nhhxz33t1#

一旦我添加了mediaType和fileName,它就工作了。我不知道为什么浏览器在网络跟踪中不显示该字段,但当我让它显示未解析的数据时,它沿着在那里。

相关问题