我试图用Django 1.10实现jQuery File Upload。我通读了wiki和其他尝试,但我想使用与wiki中列出的方法不同的方法,因此我无法重用它们的实现。我的设置是他们选择文件,填写其他一些数据,然后提交表格。发布数据进入视图,处理分块上传并创建跟踪器对象。
当我添加文件时(正在添加到显示文件的表中),文件被识别,但它们没有进入视图。 html / view是链接的,但是当我在视图中检查发布数据时,文件列表为空。
HTML:
<form id="fileupload" action="." method="POST" enctype="multipart/form-data">{% csrf_token %}
<!-- Redirect browsers with JavaScript disabled to the origin page -->
<noscript><input type="hidden" name="redirect" value="/no_javascript/"></noscript>
<div class="row">
<input type="file" id="files_picker" name="files[]" multiple class="input_hidden">
<div class="btn btn-success" onclick="clickAdd()">
<span>Add Files</span>
</div>
<!-- The loading indicator is shown during file processing -->
<span class="fileupload-loading"></span>
</div>
<!-- The global progress state -->
<div class="fileupload-progress fade">
<!-- The global progress bar -->
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-success" style="width:0;"></div>
</div>
<!-- The extended global progress state -->
<div class="progress-extended"> </div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="alternating-table">
<tbody class="files"></tbody>
</table>
// other inputs
<div class="row">
<button class="btn btn-primary" id="upload_submit" onclick="clickStarts();">
<span>Start Upload</span>
</button>
</div>
</form>
包括js:
<script src="{% static 'js/upload/jquery.ui.widget.js' %}"></script>
<script src="{% static 'js/upload/tmpl.min.js' %}"></script>
<script src="{% static 'js/upload/load-image.all.min.js' %}"></script>
<script src="{% static 'js/upload/canvas-to-blob.min.js' %}"></script>
<script src="{% static 'js/upload/jquery.blueimp-gallery.min.js' %}"></script>
<script src="{% static 'js/upload/jquery.iframe-transport.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload-process.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload-image.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload-audio.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload-video.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload-validate.js' %}"></script>
<script src="{% static 'js/upload/jquery.fileupload-ui.js' %}"></script>
<script src="{% static 'js/upload/fileupload-main.js' %}"></script>
<script src="{% static 'js/upload/locale.js' %}"></script>
<script src="{% static 'js/upload/custom-upload.js' %}"></script>
文件上传-main.js:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
});
定制upload.js:
//simulate click on file input button
function clickAdd() {
$('#files_picker').click();
}
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
uploadTemplateId: 'template-upload',
downloadTemplateId: 'template-download'
});
});
function clickStarts() {
$("#fileupload").validate();
if ($("#fileupload").valid()) {
$('.start').click();
$('#fileupload').fileupload('send', {files: filesList});
}
}
视图:
def upload(request):
if request.method == 'POST':
files = request.FILES.getlist('files')
for f in files:
handle_uploaded_file(f)
# create upload object
Upload(name=f.name, file=f, date=datetime.now().date(), ...).save()
return render(request, 'upload.html', {})
class UploadDeleteView(DeleteView):
model = Upload
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.delete()
response = JSONResponse(True, mimetype=response_mimetype(request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
class UploadListView(ListView):
model = Upload
def render_to_response(self, context, **response_kwargs):
files = [serialize(p) for p in self.get_queryset()]
data = {'files': files}
response = JSONResponse(data, mimetype=response_mimetype(self.request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
def handle_uploaded_file(f):
"""
Handles uploaded files
Reads in chunks and sends them off to their destination
"""
import os
# write file to uploads folder
path = os.path.join('/uploads/', f.name)
with open(path, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
上传模型:
class Upload(models.Model):
class Meta:
verbose_name = "Upload"
verbose_name_plural = "Uploads"
# name of file
name = models.CharField('Name', max_length=100)
# file
file = models.FileField(upload_to="/uploads")
# Date uploaded
date = models.DateField('Date Uploaded', default=None)
# others
def __str__(self):
return self.name
def delete(self, *args, **kwargs):
self.file.delete(False)
super(Upload, self).delete(*args, **kwargs)