Glandalf
Glandalf

Reputation: 107

How could I remove a strange header within an AJAX uploaded image with Django

I want to upload an image from JS/jQuery client to a Django server. For some reasons, I can't achieve to do this with a model. So I tried it the old way...

Problem: when I upload the file, the produced file contains a part of the HTTP request(?!).

Here is my Js code:

data = new FormData($('#upform-' + target.getAttribute('data-store'))[0]);
contentType = false
[...]
$.ajax({
    type: "POST",
    scriptCharset: "utf-8",
    contentType: contentType,
    dataType: 'json',
    method: "POST",
    processData: false,
    cache: false,
    data: data,
    url: "api/" + url,
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", 'Token ' + application.api.token);
        if( target ) {
            request.setRequestHeader("Content-Disposition", 'attachment; filename=' + target.files[0].name);
            request.overrideMimeType("multipart/form-data");
        }
        console.log("Données envoyées : ", data);
    }
})
...

Here is my Python view:

    myfile = request.FILES['file']
    outputFile = open(myfile.name, 'wb+')
    rawContent = ContentFile(myfile.read())
    for chunk in rawContent.chunks():
        outputFile.write(chunk)
    outputFile.close()

Here is the strange header at the beginning of my "new" file when I open it with Notepad:

-----------------------------76672927332420
Content-Disposition: form-data; name="file"; filename="planning.jpg"
Content-Type: image/jpeg

ÿØÿà 

The end of the file also contains a "------------------------".

Thanks for your help, it drives me crazy! Thank

Upvotes: 0

Views: 480

Answers (2)

Glandalf
Glandalf

Reputation: 107

As some of you suggested, it was probably because of a malformed HTTP request. By the way, I didn't find how to solve it. So I adjusted a solution proposed on this question to manually remove the header:

if request.FILES['file']:
    myfile = request.FILES['file']
    fs = FileSystemStorage()

    # building a temporary file was the solution:
    with tempfile.TemporaryFile() as tmp:
        lines = myfile.readlines()
        tmp.writelines(lines[4:-2])
        tmp.seek(0)
        fs.save(myfile.name, tmp)

It now works like a charm.

Upvotes: 1

Barmar
Barmar

Reputation: 781370

Get rid of this:

    request.setRequestHeader("Content-Disposition", 'attachment; filename=' + target.files[0].name);

This is making the server treat the entire FormData as the file being upload, rather than just the file element.

Upvotes: 0

Related Questions