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

Hello guys how are you all? Hope you all are fine. When we work with the servers and using backend then we need to upload images to server from our app. So in this tutorial we are going to learn How to upload images and file to a server in Flutter?. Lets start this tutorial without wasting your time.

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

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

    To upload images and files to a server in Flutter we have multiple methods we can upload images to server by Using MultipartRequest class, we cal also use using http Plugin And Dio Plugins Here is the example given below.

  2. upload images and file to a server in Flutter

    To upload images and files to a server in Flutter we have multiple methods we can upload images to server by Using MultipartRequest class, we cal also use using http Plugin And Dio Plugins Here is the example given below.

Method 1 : 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;

Method 2: using http

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);
}

Method 3: 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}");
  }

So, It’s All About this tutorial. I hope this tutorial helps you to solve your error. Please Comment Below if You stucks anywhere with my code.

Also Check Out Below Tutorials

Leave a Comment

  Canva Pro Crack Filmora Pro Crack Spotify Premium Free Download Tradingview Premium Free