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

Viewed 2807

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.

2 Answers

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()

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.

Related