request.FILES为空

时间:2019-10-06 14:52:30

标签: python django

我有一个带有<input type="file">的表单,用于选择要上载的图像,单击了上载按钮后,将发送POST XMLHttpRequest,该调用调用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>

1 个答案:

答案 0 :(得分:2)

您需要分别附加每个文件。

var fd = new FormData();
var files = document.getElementById('fileToUpload').files;
for (var x=0; x < files.length; x++) {
    fd.append("fileToUpload", files[x]);
}