通过 Flutter App 中的 PreSigned URL 将文件上传到 S3。但是当我下载它时文件已损坏

Bal*_*aji 5 amazon-s3 amazon-web-services pre-signed-url flutter

我正在开发 Flutter 应用程序,在其中使用预签名 URL 将图像文件(PUT 请求)上传到 AWS S3。上传成功,因为我可以在 S3 中看到文件。但是当我单击并从存储桶中下载它时,下载的文件已损坏。

我正在使用 Dio 库上传文件。通过邮递员将图像文件上传为二进制文件非常有效

uploadFileToPresignedS3(
    File payload, String fileName, String presignedURL) async {
  try {
    Dio dio = new Dio();

    FormData formData = new FormData.from(
        {"name": fileName, "file1": new UploadFileInfo(payload, fileName)});
    dio.put(presignedURL, data: formData);
  } catch (ex) {
    print(ex);
  }
}


Run Code Online (Sandbox Code Playgroud)

预期:上传的文件不会被破坏

实际结果:上传的文件已损坏

Rab*_*han 7

使用此代码使用 Dio 将文件(图像)上传到 S3 预签名 url 并显示上传进度

await dio.put(
    url,
    data: image.openRead(),
    options: Options(
      contentType: "image/jpeg",
      headers: {
        "Content-Length": image.lengthSync(),
      },
    ),
    onSendProgress: (int sentBytes, int totalBytes) {
      double progressPercent = sentBytes / totalBytes * 100;
      print("$progressPercent %");
    },
  );
Run Code Online (Sandbox Code Playgroud)

注意:不要像这样设置Content-Type标头和Content-Length

headers: {
   "Content-Length": image.lengthSync(),
   "Content-Type": "image/jpeg",
},
Run Code Online (Sandbox Code Playgroud)

由于某种原因,它会导致上传的文件损坏。

以防万一:代替print("$progressPercent %")您可以使用setState()在 UI 中显示更新。

希望这可以帮助。