[英]Ajax File Upload Django
I have a form with an input file and need to upload the file asynchronously to Django, but is not working with ajax. 我有一个带有输入文件的表单,需要将文件异步上传到Django,但无法使用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: 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: Django的:
def upload(request):
print(request.FILES)
Django returns: Django返回:
<MultiValueDict: {}>
Console JS: 控制台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? 我究竟做错了什么?
I could make it work by sending the form data to the same view. 我可以通过将表单数据发送到同一视图来使其工作。 Honestly do not know what happened. 老实说不知道发生了什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.