Search code examples
pythondjangoflutterdjango-rest-frameworkmultipartform-data

Flutter WEB sending file to Django Rest Framework Backend


So in my flutter front end (WEB). I am using Image_picker and then image_cropper packages to obtain a file.

I know flutter web doesn't support Dart/io so instead you have to send your image in a mulitpart request FromBYtes. Normally for an ios/android flutter app you can use fromFile. Now I send that to my backend as bytes. however, my django rest framework view isnt able to save the image to my model.

here is the code and step by step:

final imagetoSendToAPIasbytes = await cropImageFile.readAsBytes();
List<int> imageaslistint = imagetoSendToAPIasbytes.cast();

final response = await uploadImage(imageaslist,  profileid);

uploadimage function:

var profilepic = await http.MultipartFile.fromBytes(
          "profilepic", imageaslistint);
request.files.add(profilepic);
http.StreamedResponse response = await request.send();

var responseByteArray = await response.stream.toBytes();

ofcourse this is not the full code. But I am able to send it to the back end. my django backend view to handle:

@api_view(['PATCH', ])
@throttle_classes([updateprofileprofilepicThrottle])
@parser_classes((MultiPartParser, FormParser, JSONParser))
def updateprofileprofilepic(request,):
    try:
        user = request.user
    except User.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    try:
        if request.method == "PATCH":
            
            profileobjid= json.loads(request.data['profileid'])
            
            profileobj = Profile.objects.get(creator = user, id = profileobjid)
            
            profileobj.profilepic.delete(False)
            
            print(request.FILES['profilepic'])
            print(json.loads(request.data['profilepic']))
            profileobj.profilepic=  json.loads(request.data['profilepic'])
            profileobj.save()

usualy (request.FILES['profilepic']) allows me to save a file (from ios/android)

however thats when its sending as a mulitipart request.fromPATH.

So now (json.loads(request.data['profilepic'])) im able to get the bytes? but How do I handle saving that into an IMAGE on my model. Thank you, any help would be appreciated

<QueryDict: {'profileid': ['"xxxx-xxxx-xxxxxxxe-xxxxxxx"'], 'profilepic': ['�PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01........

do I have to convert the bytesarray back into an image in the backend?


Solution

  • so i figured it out. when making that call from Flutter WEB YOU MUST include: var profilepic = await http.MultipartFile.fromBytes( "profilepic", file, filename: 'hello.png');

    The filename. this is needed for django restframework and multiformparser to be able to save it as image.