Django JQuery Ajax 文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20822823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:19:56  来源:igfitidea点击:

Django JQuery Ajax File Upload

jqueryajaxdjangodjango-forms

提问by arnm

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

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

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

我不断收到无效表格,说我错过了“file_source”。

Why is "file_source" not getting posted?

为什么“file_source”没有发布?

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?

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

Django Form:

姜戈形式:

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

Django Template (renders form):

Django 模板(呈现形式):

<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 Upload:

JQuery/Ajax 上传:

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

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

Django View Which recieves POST:

接收 POST 的 Django 视图:

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/')

回答by arnm

Here is what I changed to get it working.

这是我为了让它工作而改变的。

  1. I used FormData to package up data from form

  2. 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.

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

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

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 View:

姜戈视图:

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/')

回答by Abdallah Okasha

Here's how we can send json data in addition to files using Ajax to Django.

下面是我们如何使用 Ajax 向 Django 发送除文件之外的 json 数据。

Example:

例子:

JS using form-data

JS 使用表单数据

var formData = new FormData();
formData.append('file1', myFile); 
const data_ = JSON.stringify(data)
formData.append('data', data_);

doPost(url, formData)
.then(result => {
 })

Django using request.FILES & request.POST

Django 使用 request.FILES 和 request.POST

data = json.loads(request.POST.get('data'))
 files = request.FILES
 attached_file1 = files.get('file1', None)
 attr1 = data.get('attr1', None)

回答by Jon Snow

You can't use jQuery to upload files asynchronously. You options are:

您不能使用 jQuery 异步上传文件。您的选择是:

1.Submit the form "the usual way". This, of course, will refresh the page.

1.提交表格“常规方式”。这当然会刷新页面。

2.Use XHR: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequestbut beware that it's not supported on IE 8/9 . On those browsers you would need to fall back to an iframe and a form that posts to it, to mimic an asynchronous upload.

2.使用 XHR:https: //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest但请注意 IE 8/9 不支持它。在这些浏览器上,您需要回退到 iframe 和发布到它的表单,以模拟异步上传。

3.Use https://github.com/blueimp/jQuery-File-UploadIt does what I described in 2. but spares you all the configuring.

3.使用https://github.com/blueimp/jQuery-File-Upload它执行我在 2. 中描述的内容,但省去了所有配置。