[英]request.FILES is empty
I have a form with an <input type="file">
for selecting images to upload, and once upload button is clicked, a POST XMLHttpRequest is sent which calls the upload_view
that should save the images on the server.我有一个带有
<input type="file">
的表单,用于选择要上传的图像,一旦单击上传按钮,就会发送一个 POST upload_view
调用应该将图像保存在服务器上的 upload_view。 However, my request.FILES
is empty for some reason.但是,由于某种原因,我的
request.FILES
是空的。 When I console.log(document.getElementById('fileToUpload').files
I can see the files there. And my request.POST
looks like this:当我
console.log(document.getElementById('fileToUpload').files
可以看到那里的文件。我的request.POST
看起来像这样:
<QueryDict: {'fileToUpload': ['[object FileList]'], 'csrfmiddlewaretoken': ['bOjUFzTnMVbHOWOQURj2egJuRizsVJIBMSfQra4yuz7MX3DOEaRPHbMVnY8xyIsU']}>
My view:我的观点:
def upload_view(request):
key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}'
for file in request.FILES.getlist('fileToUpload'):
TemporaryImage.objects.create(image=file, key=key)
return HttpResponse('complete')
My JS:我的 JS:
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files);
var value = [];
document.getElementsByName('csrfmiddlewaretoken').forEach(function(x) {
value.push(x.value);
})
fd.append('csrfmiddlewaretoken', value[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", Urls['upload-view']());
xhr.send(fd);
}
My form:我的表格:
<form id="form1" enctype="multipart/form-data" method="post">
{% csrf_token %}
<label for="fileToUpload">Select a File to Upload</label>
<input type="file" multiple="multiple" name="fileToUpload" id="fileToUpload">
<input type="button" onclick="uploadFile()" value="Upload">
</form>
You need to append each file individually.您需要 append 每个文件单独。
var fd = new FormData();
var files = document.getElementById('fileToUpload').files;
for (var x=0; x < files.length; x++) {
fd.append("fileToUpload", files[x]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.