MM YFI
MM YFI

Reputation: 67

How to upload image file using Multipart?

I tried to upload my profile Image file with cookie to my server. But I don't know how to upload it.

Here is my code:

  _submit() async {
    Api.updateUserProfileImage(
      context,
      _image,
      await Provider.of<AccountState>(context, listen: false)
          .storage
          .read(key: "cookie"),
    );
  }
  static void updateUserProfileImage(
      BuildContext context, File image, String cookie) async {}

Upvotes: 3

Views: 8028

Answers (2)

Blasanka
Blasanka

Reputation: 22477

Here is what documentation contains with an example:

A multipart/form-data request.

Such a request has both string fields, which function as normal form fields, and (potentially streamed) binary files.

This request automatically sets the Content-Type header to multipart/form-data. This value will override any value set by the user.

var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri) // your uri / url (encoded)
  ..fields['user'] = 'nweiz@google.com' // your fields key - value
  ..files.add(await http.MultipartFile.fromPath(
      'package', 'build/package.tar.gz',
      contentType: MediaType('application', 'x-tar'))); // your file(s)
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!'); // what should be done when success

Note that there is a pacakge powerful Http client for Dart/Flutter called dio which support File download and FormData.

Here is its documentation example:

Sending FormData:

FormData formData = new FormData.fromMap({
    "name": "wendux",
    "age": 25,
    "file": new UploadFileInfo(new File("yourfile.extension"), "filename.extension") // if you a file is type of file then no need to create File()
  });
response = await dio.post("/info", data: formData);

Upvotes: 0

Hardik Kumbhani
Hardik Kumbhani

Reputation: 2021

var request = http.MultipartRequest(
                    "POST",
                    Uri.parse(
                      "YourAPILINK",
                    ),
                  );
                  Map<String, String> headers = {
                    'Content-Type': 'multipart/form-data',
                    'token': token
                  };
                  request.headers['token'] = token;
                  request.headers["Content-Type"]='multipart/form-data';
                  request.fields["name"] = "hardik";

                  request.fields["email"] = "h@gmail.com";
                  request.fields["mobile"] = "00000000";
                  request.fields["address"] = "afa";
                  request.fields["city"] = "fsf";

                  if (image != null) {
                    print(image.path.split(".").last);
                    request.files.add(
                      http.MultipartFile.fromBytes(
                        "avatar",
                        image.readAsBytesSync(),
                        filename: "test.${image.path.split(".").last}",
                        contentType: MediaType(
                            "image", "${image.path.split(".").last}"),
                      ),
                    );
                  }
                  request.fields["reminder_interval"] = "1";

                  request.send().then((onValue) {
                    print(onValue.statusCode);

                    print(onValue.headers);
                    print(onValue.contentLength);
                  });

Upvotes: 3

Related Questions