我正在尝试在Django中上传多个文件,并通过DropzoneJS将它们存储在系统中。我在request.FILES中的MultiValueDict字典中获取文件。但是,它看起来像:
<MultiValueDict: {u'file[1]': [<TemporaryUploadedFile: DSC07077.jpg (image/jpeg)>], u'file[0]': [<TemporaryUploadedFile: DSC06856.JPG (image/jpeg)>]}>
上传的文件不在同一个密钥中,因此我无法使用request.FILES.getlist(&#39; file&#39;),我不知道该怎么办。
我的观点功能是:
def upload_files(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
print request.FILES
if request.FILES:
for f in request.FILES.getlist('file'):
handle_uploaded_file(f)
return HttpResponseRedirect('/swupdate/index/')
def handle_uploaded_file(f):
with open( settings.MEDIA_ROOT + f.name, 'wa') as destination:
for chunk in f.chunks():
destination.write(chunk)
我的表格:
class UploadFileForm(forms.Form):
file = forms.FileField()
我的模板表单:
<form id="my-awesome-dropzone" class="dropzone" action='/index/upload_files/' method="post" enctype="multipart/form-data">
{% csrf_token %}
<!-- Now setup your input fields -->
<input type="email" name="username" />
<input type="password" name="password" />
<div class="dropzone-previews"></div> <!-- this is were the previews should be shown. -->
<button id='SubmitAll' type="submit">Submit data and files!</button>
</form>
<script src="{% static 'js/dropzone.js' %}"></script>
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
addRemoveLinks: true,
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
非常感谢
答案 0 :(得分:1)
我不确定为什么文件会以不同的键添加到dict中,但您可以执行以下操作:
for key in request.FILES: # So each iteration, key will have the key of the dict
在您的代码中,您应该尝试:
# Your code ......
for key in request.FILES:
handle_uploaded_file(request.FILES[key])
return HttpResponseRedirect('/swupdate/index/')
# ... Your code ...