Uploading File(Image/Video) To The Server Using Multipart With Http In Flutter/Dart.

Hello everyone

In this article I’ll show you how to upload a file(image/video) to the server in form of multipart. Multipart means file will be distributed in parts, then will be uploaded to the server. For this task, we are using http restful client. First we need to add http package like this.

pubspec.yaml

http: ^0.12.2

get dependency using

 flutter pub get

imports

import 'package:http/http.dart';

Now we are ready, the code below used to create multipart-post request

var request = new http.MultipartRequest(
"POST", Uri.parse('your api url here'));

Adding file path to the request, where ‘profile_pic’ is the key for your file. You can use your key accordingly.

request.files
.add(await http.MultipartFile.fromPath('profile_pic', imagePath.path));

You can also add more fields to your request like that.

request.fields['name'] = 'Rohan';
request.fields['title'] = 'My first image';

By using the code snippet below, we can create a complete file uploading request to upload file to server in form of multipart.

void uploadFileToServer(File imagePath) async {
var request = new http.MultipartRequest(
"POST", Uri.parse('your api url her'));
request.fields['name'] = 'Rohan';
request.fields['title'] = 'My first image';
request.files.add(await http.MultipartFile.fromPath('profile_pic', imagePath.path));
request.send().then((response) {
http.Response.fromStream(response).then((onValue) {
try {
// get your response here...
} catch (e) {
// handle exeption
}
});
});
}

Just call this method where you want to upload data to the server. Thanks for reading..

If you liked this article, don’t forget to Clap

Happy Coding !!

Flutter Developer Since 2020

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store