Javascript 如何在POST上使用Ajax上传文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44708023/
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
How to upload a file using Ajax on POST?
提问by Hiroyuki Nuri
I know, the topics aren't missing on this subject but bear with me. I'd like to upload a file to the server using Ajax or an equivalent.
我知道,关于这个主题的主题并没有丢失,但请耐心等待。我想使用 Ajax 或等效工具将文件上传到服务器。
# html
<form method="post" id="Form" enctype="multipart/form-data">
{% csrf_token %} # django security
<input id="image_file" type="file" name="image_file">
<input type="submit" value="submit">
</form>
# javascript
$(document).on('submit', '#Form', function(e){
e.preventDefault();
var form_data = new FormData();
form_data.append('file', $('#image_file').get(0).files);
$.ajax({
type:'POST',
url:'my_url',
processData: false,
contentType: false,
data:{
logo:form_data,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security
},
});
});
# views.py (server side)
def myFunction(request):
if request.method == 'POST':
image_file = request.FILES
...
...
I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo.
我想我配置 ajax 函数的方式存在问题,因为在调试模式下,除了logo.
Am I doing something incorrectly?
我做错了什么吗?
采纳答案by Hiroyuki Nuri
Looking back, the older answer is unpractical and not recommended. asnyc: falsepauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
回想起来,旧的答案是不切实际的,不推荐。asnyc: false暂停整个 Javascript 以简单地上传文件,您可能会在上传过程中触发其他功能。
If you are using JQuery solely for the use of ajax, then I recommand using axios:
如果您仅使用 JQuery 来使用ajax,那么我建议使用axios:
const axios = require('axios');
var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);
axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});
AxiosDocumentation
Axios文档
Jquery/Ajax answer:
Jquery/Ajax 答案:
var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});
Jquery/AjaxDocumentation
回答by Mahesh Singh Chouhan
The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POSTand logo request.FILES
以下方法适用于我,它将所有表单值提交为serialize(). 您将获得所有表单输入的内部request.POST和徽标request.FILES
Try this:
尝试这个:
$(document).on('submit', '#creationOptionsForm', function(e){
e.preventDefault();
var form_data = new FormData($('#creationOptionsForm')[0]);
$.ajax({
type:'POST',
url:'/designer/results/',
processData: false,
contentType: false,
async: false,
cache: false,
data : form_data,
success: function(response){
}
});
});
Update:
更新:
basically async:falsewill do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.
基本上async:false会执行ajax请求并停止执行进一步的js代码,直到请求完成,因为上传文件可能需要一些时间才能上传到服务器。
While cachewill force browser to not cache uploaded data to get updated data in ajax request
虽然cache会强制浏览器不缓存上传的数据以在 ajax 请求中获取更新的数据
官方文档在这里

