Flutter/Dart: Automatically set images Uploaded to S3 Bucket as "image/jpeg"?
Asked Answered
S

1

1

Whenever I upload image files to my bucket from my Flutter app, the object automatically appears in metadata as "binary/octet-stream" rather than the "image/jpeg" category which I need.

The code I'm using looks like this;

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;

How do I get the photos automatically uploaded as "image/jpeg" so that they can be viewed in a browser instead of downloaded to my desktop?

Spirula answered 2/5, 2021 at 9:36 Comment(0)
M
1

You can append a media contentType: new MediaType('image', 'jpeg') type as shown below

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

dont forget to import import 'package:http_parser/http_parser.dart';

Mcclary answered 2/5, 2021 at 9:43 Comment(5)
Should that code be a drop in replacement for; http.MultipartFile('file', stream, length, filename: path.basename(file.path) ?Spirula
you just need to add this to yout Multipart contentType: new MediaType('image', 'jpeg')Mcclary
I tried this; final multipartFile = http.MultipartFile('file', stream, length, filename: path.basename(file.path), contentType: new MediaType('image', 'jpeg')); But I got this error; /C:/flutter/.pub-cache/hosted/pub.dartlang.org/aws_s3_upload-1.1.2/lib/aws_s3_upload.dart:47:26: Error: Method not found: 'MediaType'. contentType: new MediaType('image', 'jpeg')Spirula
you need to import http_parser import 'package:http_parser/http_parser.dart';Mcclary
That really should've worked and showed no errors on execution, but unfortunately the uploaded image file is still registered as "binary/octet-stream" under the S3 object's metadata content-type property.Spirula

© 2022 - 2024 — McMap. All rights reserved.