我有一个表单,其中包含<input type="file">用于选择要上传的图像的表单,单击上传按钮后,将发送 POST XMLHttpRequest,该表单调用upload_view应将图像保存在服务器上的表单。但是,request.FILES出于某种原因,我的表单为空。当我console.log(document.getElementById('fileToUpload').files看到那里的文件时。我的request.POST表单如下所示:
<input type="file">
upload_view
request.FILES
console.log(document.getElementById('fileToUpload').files
request.POST
<QueryDict: {'fileToUpload': ['[object FileList]'], 'csrfmiddlewaretoken': ['bOjUFzTnMVbHOWOQURj2egJuRizsVJIBMSfQra4yuz7MX3DOEaRPHbMVnY8xyIsU']}>
我的观点:
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')
我的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); }
我的表格:
<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>
您需要单独附加每个文件。
var fd = new FormData(); var files = document.getElementById('fileToUpload').files; for (var x=0; x < files.length; x++) { fd.append("fileToUpload", files[x]); }