How To: Upload Images and Files To Server Flutter

Haris Bin Nasir Avatar

·

·

In this post, I’ll teach you how to upload files to a server using Flutter. The term “multipart” refers to a file that will be dispersed in sections before being uploaded to the server. We’re going to use the http restful client for this. First, we’ll need to install the http package, which may be found here.

When working with servers and backends in Flutter, we sometimes require to upload a file such as photos or videos from our Flutter app to a server. So, in this tutorial, we’ll see how to upload photos and files to a server using Flutter. So without anything further to do let’s get into it.

How To Upload Images and Files to a Server using Flutter?

To upload files and images we can utilize plugins such as http or Dio and use the provided MultipartRequest class. Below you’ll find some methods on uploading a file to a server using Flutter.

Using MultipartRequest Class

Upload(File imageFile) async {    
    var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      var length = await imageFile.length();

      var uri = Uri.parse(uploadURL);

     var request = new http.MultipartRequest("POST", uri);
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));
          //contentType: new MediaType('image', 'png'));

      request.files.add(multipartFile);
      var response = await request.send();
      print(response.statusCode);
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }

The namespace will look like below:

import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;

Using http – Upload Files To Server Flutter

import 'dart:io';
import 'package:http/http.dart' as http;

_asyncFileUpload(String text, File file) async{
   //create multipart request for POST or PATCH method
   var request = http.MultipartRequest("POST", Uri.parse("<url>"));
   //add text fields
   request.fields["text_field"] = text;
   //create multipart using filepath, string or bytes
   var pic = await http.MultipartFile.fromPath("file_field", file.path);
   //add multipart to request
   request.files.add(pic);
   var response = await request.send();

   //Get the response from the server
   var responseData = await response.stream.toBytes();
   var responseString = String.fromCharCodes(responseData);
   print(responseString);
}

Using Dio Plugin

uploadFileFromDio(UserProfile userProfile, File photoFile) async {
    var dio = new Dio();
    dio.options.baseUrl = url;
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout = 5000;
    dio.options.headers = <Header Json>;
    FormData formData = new FormData();
    formData.add("user_id", userProfile.userId);
    formData.add("name", userProfile.name);
    formData.add("email", userProfile.email);

    if (photoFile != null &&
        photoFile.path != null &&
        photoFile.path.isNotEmpty) {
      // Create a FormData
      String fileName = basename(photoFile.path);
      print("File Name : $fileName");
      print("File Size : ${photoFile.lengthSync()}");
      formData.add("user_picture", new UploadFileInfo(photoFile, fileName));
    }
    var response = await dio.post("user/manage_profile",
        data: formData,
        options: Options(
            method: 'POST',
            responseType: ResponseType.PLAIN // or ResponseType.JSON
            ));
    print("Response status: ${response.statusCode}");
    print("Response data: ${response.data}");
  }

Conclusion

I hope you found this tutorial on how to upload a file to a server using HTTP request and Flutter useful. Now you can easily upload files such as Images, Videos, PDF etc to a remote server that support file uploading.

There may be several articles on the subject of uploading a file to a server from a flutter app. However, I adopted the route of using easily accessible plugins to achieve this task, so that focus can be places upon uploading the content rather than writing a bunch of boilerplate code.

As always, If you have found this tutorial useful do not forget to share it and leave a comment if you have any questions. Happy Coding

Leave a Reply

Your email address will not be published. Required fields are marked *