Django JQuery Ajax 文件上传 [英] Django JQuery Ajax File Upload

查看:32
本文介绍了Django JQuery Ajax 文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几个小时以来一直在尝试上传一个简单的文本文件,但似乎仍然无法正常工作.

I've been trying to upload a simple text file for hours now but I still can't seem to get it working.

我不断收到无效表单,说我缺少file_source".

I keep getting invalid forms saying I'm missing the "file_source".

为什么file_source"没有被发布?

Why is "file_source" not getting posted?

我也让它实际发送file_source",但它仍然说它丢失了.应该为 Django FileFiled 提供什么类型的元素?

I've also got it to actually send "file_source" but it still says it is missing. What type of element should be given to a Django FileFiled?

Django 表单:

class FileUploadForm(forms.Form):
    file_source = forms.FileField()

Django 模板(渲染表单):

Django Template (renders form):

<form action="/upload/" method="post" id="file-upload-form" enctype="multipart/form-data"> {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary" id='upload-btn'>Upload</button>
</form>

JQuery/Ajax 上传:

JQuery/Ajax Upload:

function uploadFile() {
$.ajax({
    data: $(this).serialize(),
    type: $(this).attr('method'),
    url: $(this).attr('action')
});
return false;
}

$(function() {
     $('#file-upload-form').submit(uploadFile);
});

接收 POST 的 Django 视图:

Django View Which recieves POST:

def upload_view(request):
if request.is_ajax():
    form = FileUploadForm(request.POST)
    if form.is_valid():
        print 'valid form'
    else:
        print 'invalid form'
        print form.errors
return HttpResponseRedirect('/ingest/')

推荐答案

这是我为使其正常工作所做的更改.

Here is what I changed to get it working.

  1. 我使用FormData从表单中打包数据

  1. I used FormData to package up data from form

注意 Django 视图中表单的参数.我之前没有指定文件",这就是导致需要文件字段"错误的原因.

Notice the parameters of the form in the Django view. I was not specifying "files" before and that's what caused the " file field required" error.

Javascript:

Javascript:

function upload(event) {
event.preventDefault();
var data = new FormData($('form').get(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_view(request):
    if request.method == 'POST':
        form = FileUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            print 'valid form'
        else:
            print 'invalid form'
            print form.errors
    return HttpResponseRedirect('/ingest/')

这篇关于Django JQuery Ajax 文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆