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

时间:2018-04-20 01:15:06

标签: jquery ajax django upload

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

2 个答案:

答案 0 :(得分:0)

摆脱这个:

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

这使服务器将整个FormData视为正在上传的文件,而不仅仅是file元素。

答案 1 :(得分:0)

正如你们中的一些人所说,这可能是因为HTTP请求格式错误。顺便说一句,我没有找到如何解决它。所以我调整了在这个问题上提出的解决方案来手动删除标题:

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)

它现在就像一个魅力。