Decoding error when uploading file from Flutter frontend to Django backend

Issue

I would like to upload an image from flutter frontend to a python (django) server.

I’ve been trying to debug this for longer than I’d like to admit. There are no resources online which show how to handle uploading a file from Flutter to Django backend.

The backend is receiving the file, but I’m getting a UTF-8 decoding error when the file is being saved to local storage.

This is the specific error I get when I try to upload an image:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte.

I have included the complete traceback in this pastebin.

This is the file information as it is received by the backend:

{'file': <_io.BytesIO object at 0x7fe121a44f50>,
 '_name': 'tempProfilePic.jpg',
 'size': 311489, 
 'content_type': 'application/octet-stream',
 'charset': None,
 'content_type_extra': {},
 'field_name': 'file'}

Below is my frontend code:

if (_imageFile != null) {
  var stream =
      http.ByteStream(DelegatingStream.typed(_imageFile.openRead()));
  var length = await _imageFile.length();
  var multipartFile = http.MultipartFile('file', stream, length,
      filename: basename(_imageFile.path));
  request.files.add(multipartFile);
}
request.fields['token'] = token
var response = await request.send();

_imageFile is a File variable which contains a .png image saved in storage. The file is sent without any error.

Below is my backend code:
models.py

class userData(models.Model):
    profilePic = models.FileField(upload_to='documents/')
    token = models.CharField()

And the view element which handles the post request:
views.py

def uploadImage(request):
    currUser = userData.objects.get(token=request.data['token'])
    if request.FILES['file']:
        currUser.profilePic= request.FILES['file']

If what I’m doing currently seems too difficult to debug, are there easier ways I can approach this? (e.g. sending the file as a string from frontend?)

(FYI, I need a backend for other functionality and cannot use serveless or firebase approaches. All other functionalities are done under Django. Implementing File upload is one of the last things I’ve got left).

I can supply any additional information if needed.

Thank you for your help.


There are several questions mentioning the UTF-8 decoding error, none of which are comprehensive or contain enough code for me to be able to debug my use case. And they don’t seem to be using django models. I’ve been at this for several days, and have tried several of these, yet wasn’t able to implement any of them. A nudge in the right direction would appreciated.

Solution

It’s shamefully dumb, but the correct answer is to open the file before uploading it:

currUser.profilePic= request.FILES['file'].open()

Answered By – poultrynews

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *