2

How can we upload images(.jpg, .png) to Azure blob storage. Not getting any insight to start with.

If you have used example would love to see and try if that is the way to do, any working example/url would help get started with

Here is i am trying to upload .jpg file and getting 400 error,

image.forEach((element) async {
    ImageDetailsUpload result = ImageDetailsUpload.fromJson(element);
    var postUri = Uri.parse('$url/${result.fileName}?$code'); //Azure blob url
    var request = new http.MultipartRequest("PUT", postUri); //Put method
    request.files.add(
      new http.MultipartFile.fromBytes(
        'file',
        await File.fromUri(Uri.parse(result.path)).readAsBytes(),
      ),
    );
    request.send().then((response) {
      print(response.statusCode);
    }, onError: (err) {
      print(err);
    });
  });

image is a LIST and holds the fileName and File path, this is what i get as bytes (see image below)

enter image description here

Solved the issue of upload but image is being corrupted now on server -

image.forEach((element) async {
    ImageDetailsUpload result = ImageDetailsUpload.fromJson(element);
    var postUri = Uri.parse('$url/${result.fileName}?$code');
    var request = new http.MultipartRequest("PUT", postUri);
    request.headers['X-MS-BLOB-TYPE'] = 'BlockBlob';

    request.files.add(
      new http.MultipartFile.fromBytes(
        'file',
        await File.fromUri(Uri.parse(result.path)).readAsBytes(),
      ),
    );
    request.send().then((response) {
      print(response.statusCode);
    }, onError: (err) {
      print(err);
    });
  });

this seems to haunting me.

There is more to the question, what i noticed is the file uploaded using postman to blob storage are store as actual image of type image/jpeg depending on what type of image i am uploading. But when uploading using application i am using as mutipart which is making th e stored file into of type multipart/form-data. Uploaded both types of image jpg/png both gives type as mentioned above. enter image description here

[![enter image description here][3]][3]

Satish Raizada
  • 91
  • 1
  • 3
  • 6

2 Answers2

0

check here if you are using HTTP

How to upload images and file to a server in Flutter?

check this code if you are using Dio

FormData formData = FormData.from({
"name": "wendux",
"age": 25,
"file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt")
});
response = await dio.post("/info", data: formData);

and check Dio's documentation https://pub.dev/packages/dio

Here is a working example from one of my codes

Future<UploadImageResultModel> uploadImage(File image, String memberToken,
  {String type = "IMAGE"}) async {
var uri = Uri.parse('${Constants.baseUrl}member/UploadImage/$type');
var request = new http.MultipartRequest("POST", uri);

request.headers.addAll({
  "Authentication": memberToken,
});

var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
var multipartFile = new http.MultipartFile('file', stream, length,
    filename: image.path.split("/").last);

request.files.add(multipartFile);

var streamedResponse = await request.send();

var response = await http.Response.fromStream(streamedResponse);

if (response.statusCode != 200)
  return UploadImageResultModel.fromJson(json.decode("{}"));

return UploadImageResultModel.fromJson(json.decode(response.body));
}
omar hatem
  • 1,799
  • 1
  • 10
  • 23
0

First, convert the image File to Stream as data will be a push to the blob container in form of a stream.

Future uploadImage(File file) async {
    String fileName = file.path.split('/').last;
    _logger.info("File Path: " + fileName);

    String imageToken = "Get your own token";
    String containerName = "Blob container name";


    final fileBytes = file.readAsBytesSync();
    var streamData = Stream.fromIterable(fileBytes.map((e) => [e]));
    String uploadDestinationUrl = RollaConstants.HOST_IMAGE +
        "/$containerName" +
        "/$fileName" +
        imageToken;


    final Dio _dio = Dio();
    Response response;
    try {
      response = await _dio.put(uploadDestinationUrl,
          data: streamData,
          options: Options(headers: {
            Headers.contentLengthHeader: fileBytes.length,
            "x-ms-blob-type": "BlockBlob",
            "content-type": "image/jpeg"
          }));
    } catch (error, stacktrace) {
      print("Exception occured: $error.response stackTrace: $stacktrace");
    }
    print("Blob response: " + response.statusCode.toString());
  }
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147