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.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料