weixin_33749131 2015-12-17 13:14 采纳率: 0%
浏览 8

Ajax文件上传Django

I have a form with an input file and need to upload the file asynchronously to Django, but is not working with ajax. The code is as follows:

Form:

<form id="upload" method="post" action="/upload/" enctype="multipart/form-data">
<input type="file" name="test" id="test'>
<button  type="submit">Upload</button></form>

JS:

function upload(event) {
    event.preventDefault();
    var data = new FormData();
    data.append('upload',$('#test').prop('files')[0]);

    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: data,
        cache: false,
        processData: false,
        contentType: false,
        success: function(data) {
            alert('success');
        }
    });
    return false;
}

$(function() {
    $('form').submit(upload);
});

Django:

def upload(request):
    print(request.FILES)

Django returns:

<MultiValueDict: {}>

Console JS:

console.log(data.get('upload'));
File { name: "test.csv", lastModified: 1446743198000, lastModifiedDate: Date 2015-11-05T17:06:38.000Z, size: 14, type: "text/csv" }

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • weixin_33711647 2015-12-18 10:29
    关注

    I could make it work by sending the form data to the same view. Honestly do not know what happened.

    评论

报告相同问题?