Flutter sending a post request to a Django API with a file as the body

2,451

Solution 1

in flutter use

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

  @override
  Future<Map<String, dynamic>> sendFiletodjango(
      {File file,
    }) async {
    var endPoint = url;
    Map data = {};
    String base64file = base64Encode(file.readAsBytesSync());
    String fileName = file.path.split("/").last;
    data['name']=fileName;
    data['file']= base64file;
    try {
      var response = await http.post(endPoint,headers: yourRequestHeaders, body:convert.json.encode(data));
    } catch (e) {
      throw (e.toString());
    }
  }

in python django use

from django.core.files.base import ContentFile



file = response.data.get("file")
name = response.data.get("name")

your_file = ContentFile(base64.b64decode(file),name)

model.fileField = your_file
model.save()

Solution 2

You can try multipart/form-data to upload files from Flutter to the Django server using HTTP post request.

From flutter, you can send multipart/form-data request in the below shown way.

Future<Response> uploadFile(File file) async {
  Response response;
  var uri = Uri.parse(url);
  var request = http.MultipartRequest('POST', uri);
  request.files.add(await http.MultipartFile.fromPath('file', file.path));
  var response = await request.send();
  if (response.statusCode == 200 || response.statusCode == 201) {
    print('Uploaded!');
  }
  return response;
}

You can find more about it here Dart MultipartRequest.

Share:
2,451
Sorin Burghiu
Author by

Sorin Burghiu

Updated on December 24, 2022

Comments

  • Sorin Burghiu
    Sorin Burghiu 11 months

    I have a Django API where a user is able to upload a file through a post request with the following body:

    {
      "file": *attached file*
    }
    

    In Django, the file is gathered from the request with request.FILES['file']

    The request has to be sent from flutter (dart) code. I have tried a few ways, this is the function from my latest attempt which shows an error - because the "file" is not in the correct format.

    static void uploadProfilePhoto(File file, String fileId) async {
        Uint8List fileBytes = file.readAsBytesSync();
        var response = http.post(
          globals.baseURL() + "/upload/",
          //headers: {"Content-Type": "application/json"},
          body: {
            "file":base64Encode(fileBytes)
          }
        ).then((v)=>print("v: "+v.body));
      }
    

    Any idea in what format the "file" should be sent from flutter? Else is there any other method which might work? Thank you in advance.

    • Mrunal Joshi
      Mrunal Joshi almost 3 years
      Did you find a way to send the file ?
    • Sorin Burghiu
      Sorin Burghiu almost 3 years
      @MrunalJoshi sadly not, we found a workaround this using firebase
  • Piyush Maurya
    Piyush Maurya about 3 years
    If you are using django-rest-framework and having models.FileField in model, in post request, file upload will work using multipart/form-data.
  • Sorin Burghiu
    Sorin Burghiu about 3 years
    Thank you for your comment. Sadly this didnt work for me, think its because there is no rest framework for it, its just using request.FILES in django. Any idea how that may apply to this?
  • Sorin Burghiu
    Sorin Burghiu about 3 years
    Thank you for the answer, but unfortunately i cannot modify the django code, you think there is any way to get around this?
  • Piyush Maurya
    Piyush Maurya about 3 years
    Please try your post api using multipart/form-data in postman and see if it's working.
  • Piyush Maurya
    Piyush Maurya about 2 years
    @HassanAnsari Please try your post api using multipart/form-data in postman and see if it's working.