【发布时间】:2014-11-19 08:44:30
【问题描述】:
我正在尝试在 Django 中上传多个文件并通过 DropzoneJS 将它们存储在系统中。我在 request.FILES 中的 MultiValueDict 字典中获取文件。但是,它看起来像:
<MultiValueDict: {u'file[1]': [<TemporaryUploadedFile: DSC07077.jpg (image/jpeg)>], u'file[0]': [<TemporaryUploadedFile: DSC06856.JPG (image/jpeg)>]}>
上传的文件不在同一个key中,所以我不能使用request.FILES.getlist('file'),也不知道应该如何获取。
我的意见功能是:
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>
非常感谢
【问题讨论】:
-
这是我在 Django 中使用 dropzonejs 的一个小教程:DropzoneJS & Django: How to build a file upload form
-
我以前用过那个教程,但我不知道为什么,这些选项被 Django 忽略了,文件立即上传了。我像互联网上的所有教程一样混合在一起。我希望有人可以帮助我:(
标签: python django file-upload request dropzone.js