【问题标题】:Flutter/Dart: Automatically set images Uploaded to S3 Bucket as "image/jpeg"?Flutter/Dart:自动将上传到 S3 Bucket 的图像设置为“image/jpeg”?
【发布时间】:2021-05-02 09:36:30
【问题描述】:

每当我从 Flutter 应用程序将图像文件上传到我的存储桶时,该对象会自动在元数据中显示为“binary/octet-stream”,而不是我需要的“image/jpeg”类别。

我使用的代码是这样的;

String filename}) async {
    final endpoint = 'https://$bucket.s3-$region.amazonaws.com ';
    final uploadDest = '$destDir/${filename ?? path.basename(file.path)}';

    final stream = http.ByteStream(Stream.castFrom(file.openRead()));
    
    final length = await file.length();

    final uri = Uri.parse(endpoint);
    final req = http.MultipartRequest("POST", uri);
    final multipartFile = http.MultipartFile('file', stream, length,
        filename: path.basename(file.path)
        );

    final policy = Policy.fromS3PresignedPost(uploadDest, bucket, accessKey, 15, length, region: region);
    final key = SigV4.calculateSigningKey(secretKey, policy.datetime, region, 's3');
    final signature = SigV4.calculateSignature(key, policy.encode());

    req.files.add(multipartFile);
    req.fields['key'] = policy.key;
    req.fields['acl'] = 'public-read';
    req.fields['X-Amz-Credential'] = policy.credential;
    req.fields['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256';
    req.fields['X-Amz-Date'] = policy.datetime;
    req.fields['Policy'] = policy.encode();
    req.fields['X-Amz-Signature'] = signature;

如何将照片自动上传为“image/jpeg”,以便可以在浏览器中查看而不是下载到我的桌​​面?

【问题讨论】:

    标签: flutter dart amazon-s3 image-upload


    【解决方案1】:

    您可以附加一个媒体 contentType: new MediaType('image', 'jpeg') 类型,如下所示

    new http.MultipartFile.fromBytes('file', await File.fromUri("<path/to/file>").readAsBytes(), contentType: new MediaType('image', 'jpeg'))
    

    别忘了导入 import 'package:http_parser/http_parser.dart';

    【讨论】:

    • 该代码是否应该被替代; http.MultipartFile('file', stream, length, filename: path.basename(file.path) ?
    • 你只需要将这个添加到你的 Multipart contentType: new MediaType('image', 'jpeg')
    • 我试过这个; final multipartFile = http.MultipartFile('file', stream, length, filename: path.basename(file.path), contentType: new MediaType('image', 'jpeg'));但我得到了这个错误; /C:/flutter/.pub-cache/hosted/pub.dartlang.org/aws_s3_upload-1.1.2/lib/aws_s3_upload.dart:47:26:错误:找不到方法:'MediaType'。 contentType: new MediaType('image', 'jpeg')
    • 需要导入http_parser import 'package:http_parser/http_parser.dart';
    • 这确实应该有效并且执行时没有显示错误,但不幸的是,上传的图像文件仍然在 S3 对象的元数据内容类型属性下注册为“binary/octet-stream”。跨度>
    猜你喜欢
    • 2021-07-22
    • 2018-09-12
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    相关资源
    最近更新 更多