Flutter sending a post request to a Django API with a file as the body
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.
Sorin Burghiu
Updated on December 24, 2022Comments
-
Sorin Burghiu over 1 year
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 over 3 yearsDid you find a way to send the file ?
-
Sorin Burghiu over 3 years@MrunalJoshi sadly not, we found a workaround this using firebase
-
-
Piyush Maurya over 3 yearsIf you are using
django-rest-framework
and havingmodels.FileField
in model, inpost
request, file upload will work usingmultipart/form-data
. -
Sorin Burghiu over 3 yearsThank 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 over 3 yearsThank you for the answer, but unfortunately i cannot modify the django code, you think there is any way to get around this?
-
Piyush Maurya over 3 yearsPlease try your
post
api usingmultipart/form-data
in postman and see if it's working. -
Piyush Maurya over 2 years@HassanAnsari Please try your
post
api usingmultipart/form-data
in postman and see if it's working.