Quantcast
Channel: User Ciprian Tarta - Stack Overflow
Viewing all articles
Browse latest Browse all 31

Django transfer uploaded file

$
0
0

I'm trying to upload a file via django forms, then send it to an API.

Here's the encoding function:

#FYI, requestFile = request.FILES['file']def EncodeFile(self, requestFile, fields = []):    BOUNDARY    = '----------boundary------'    CRLF        = '\r\n'    body        = []    # Add the metadata about the upload first    for param in fields:        body.extend(          ['--'+ BOUNDARY,'Content-Disposition: form-data; name="%s"' % param,'',           fields[param],           ])    fileContent = requestFile.read()    body.extend(      ['--'+ BOUNDARY,'Content-Disposition: form-data; name="file"; filename="%s"'       % requestFile.name,       # The upload server determines the mime-type, no need to set it.'Content-Type: '+ requestFile.content_type,'',       fileContent,       ])    # Finalize the form body    body.extend(['--'+ BOUNDARY +'--', ''])    result =  'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)    return result

The problem is that when it reaches "CRLF.join(body)" it complains about "'utf8' codec can't decode byte 0xff in position 0: invalid start byte".

The exact same piece of code works flawlessly from the command line with the exception that the requestFile is actually a path to a file, and I'm doing an open(requestFile, 'rb') before reading the contents.

I can not for the life of me figure out what to do next. I've been googling for an answer for the past 10 hours or so.


Viewing all articles
Browse latest Browse all 31

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>