she*_*enk 16 javascript python django file-upload dropzone.js
当我使用dropzone上传文件时,它会将它们添加到数据库中,但它们没有文件,只有ID和创建日期.我认为观点是问题,但我已经尝试了很多东西,我无法弄明白.有关更详细的帐户,请参阅下面的编辑.
这是观点
@login_required(login_url='/dashboard-login/')
def dashboard(request):
current_user = request.user
current_client = request.user.client
files = ClientUpload.objects.filter(client=current_client)
form = UploadFileForm()
if request.method == 'POST':
if request.FILES is None:
logger = logging.getLogger(__name__)
logger.warning("No files were attached to the upload.")
return HttpResponseBadRequest('No Files Attached.')
if form.is_valid():
upload = form.save()
form = UploadFileForm(request.POST, request.FILES)
else:
uploaded_files = [request.FILES.get('file_upload[%d]' % i)
for i in range(0, len(request.FILES))]
for f in uploaded_files:
client_upload = ClientUpload.objects.create(client=current_client, file_upload=f)
#for key in request.FILES:
# cupload = ClientUpload.objects.create(client=current_client, file_upload=request.FILES[key])
logger = logging.getLogger(__name__)
logger.debug(request.FILES)
logger.info("File(s) uploaded from " + current_client.company)
return HttpResponseRedirect(reverse('dashboard'))
data = {'form': form, 'client': current_client, 'files': files}
return render_to_response('dashboard.html', data, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
这是我的dz选项:
url: '127.0.0.1:8003/dashboard/',
method: "post",
withCredentials: false,
parallelUploads: 12,
uploadMultiple: true,
maxFilesize: 256*4*2,
paramName: "file_upload",
createImageThumbnails: true,
maxThumbnailFilesize: 20,
thumbnailWidth: 100,
thumbnailHeight: 100,
maxFiles: 12,
params: {},
clickable: true,
ignoreHiddenFiles: true,
acceptedFiles: null,
acceptedMimeTypes: null,
autoProcessQueue: false,
addRemoveLinks: true,
previewsContainer: null,
dictDefaultMessage: "Drop files here to upload",
dictFallbackMessage: "Your browser does not support drag and drop file uploads.",
dictFallbackText: "Please use the fallback form below to upload your files.",
dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB.",
dictInvalidFileType: "You can't upload files of this type.",
dictResponseError: "Server responded with {{statusCode}} code.",
dictCancelUpload: "Cancel upload",
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
dictRemoveFile: "Remove",
dictRemoveFileConfirmation: null,
dictMaxFilesExceeded: "You can only upload {{maxFiles}} files.",
Run Code Online (Sandbox Code Playgroud)
这是模板:
{% load i18n %}
{% load staticfiles %}
{% load crispy_forms_tags %}
<link href="{% static 'css/dropzone2.css' %}" type="text/css" rel="stylesheet"/>
<form class="dropzone" id="myDropzone" method="post" action="{% url 'dashboard' %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
<button class="upload-control btn-success btn" type="submit" id='submit-all' onclick="document.getElementById('myDropzone').submit()">
<i class="glyphicon glyphicon-upload"></i>
<span>{% trans 'Submit' %}</span>
</button>
<style>
.upload-control {
margin-top: 10px;
margin-bottom: 0px;
}
</style>
<script src="{% static 'js/dropzone.js' %}"></script>
<script src="{% static 'js/jquery-2.1.4.min.js' %}"></script>
<script type="text/javascript">
Dropzone.autoDiscover = false
$(document).ready(function() {
Dropzone.options.myDropzone = {
init : function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this;
submitButton.addEventListener("click", function(e) {
e.stopPropagation();
e.preventDefault();
myDropzone.processQueue();
});
this.on("sendingmultiple", function() {
// Figure out what I want here or if I want at all
});
this.on("successmultiple", function(files, response) {
window.location.reload();
});
this.on("errormultiple", function(files, response) {
// Figure out what I want here or if I want at all
});
}
// Do I need this?
//myDropzone.on('success', myDropzone.processQueue.bind(myDropzone));
};
});
</script>
Run Code Online (Sandbox Code Playgroud)
编辑:
在将http://添加到url设置后,它现在可以正常工作.但是当我上传文件时,它会被添加到数据库中,但文件字段是空白的.多文档在我打印出来时会显示该文件,但是当它保存到数据库时,文件字段中没有任何内容.
当我上传一个文件时,我在请求中得到了这个.FILES:
<MultiValueDict: {u'file_upload[]': [<InMemoryUploadedFile: normal.PNG (image/png)>]}>
当我上传两个时,我在请求中得到了这个.FILES:
<MultiValueDict: {u'file_upload[]': [<TemporaryUploadedFile: normal.PNG (image/png)>]}>
尽管是两个文件,它只显示一个文件,但是它们都添加到数据库中(两者都没有文件,只有ID和创建日期).什么是TemporaryUploadedFile和InMemoryUploadedFile?
当我上传多个但它没有时,它应该在u'file_upload []'中有索引.我有正确的设置上传倍数.
但我似乎无法将它们从MultiValueDict中删除.当我尝试这样的事情:
for upload in request.FILES:
client_upload = ClientUpload.objects.create(client=current_client, file_upload=upload)
Run Code Online (Sandbox Code Playgroud)
我遇到了管理面板显示ID和时间但没有文件的问题.上传一个或多个时会发生这种情况.我不确定InMemoryUploadedfile和TemporaryUploadedFile之间的区别是什么.如何从MultiValueDict中提取文件?get()不起作用,使用list comp我只得到一个空列表.
另一件奇怪的事情是,当我上传某些文件时,MultiValueDict是空的,而其他文件则不是.此外,似乎我的视图不止一次被调用(根据日志输出),这是正常的,除了它应该是一个帖子然后重定向到一个获取,但它似乎有多个帖子请求.我检查了chrome中的dev工具,我只看到一个,但奇怪的是每次提交时它都会输出两次我的日志语句.我知道问题可能在我看来,但我已经尝试了很多东西,无法弄清楚出了什么问题.
有人有什么想法吗?
我自己正在使用Dropzone和Django来为每个上传的文件创建Image对象,这似乎与你想要做的类似.我想指出一些我经历过的事情,并告诉你我是如何做的,看看是否有帮助.
为了在Dropzone上传的文件在数据库中创建记录,您需要的是:
我不明白你在使用Form做什么(它只是验证?)但似乎没必要.您不需要它(并且不使用它)来实际保存文件.
首先让我们谈谈如何访问文件request.FILES.通过设置uploadMultiple: true您的悬浮窗配置,你调理悬浮窗不要送dzfile,但送表示为每个文件dzfile[%d](即dzfile[0],dzfile[1]等).
即使不是这种情况,你也在使用request.FILES,就好像它是一个list(for f in request.FILES),但就像你指出它实际上是一个字典.
这是我打印时Python显示的内容request.FILES:
<MultiValueDict: {u'dzfile[1]': [<InMemoryUploadedFile: image2.jpg (image/jpeg)>], u'dzfile[2]': [<InMemoryUploadedFile: image3.jpg (image/jpeg)>], u'dzfile[0]': [<InMemoryUploadedFile: image1.jpg (image/jpeg)>]}>
Run Code Online (Sandbox Code Playgroud)
要按名称访问get每个密钥所需的实际文件.
files = [request.FILES.get('dzfile[%d]' % i)
for i in range(0, len(request.FILES))]
Run Code Online (Sandbox Code Playgroud)
现在你有了你想要的文件列表.只需遍历它并根据需要创建对象即可.我不确定你的模型是如何工作的所以我将要近似.
for f in files:
# Create a ClientUpload object by setting its FK to client and
# FileField to the file. Correct me if I deduced the models incorrectly
client_upload = ClientUpload.objects.create(
client=current_client,
file_upload=f,
)
Run Code Online (Sandbox Code Playgroud)
这应该足以创建您想要的对象.
似乎在Click事件监听器中添加了您必须添加的提交按钮
e.preventDefault();
e.stopPropagation();
Run Code Online (Sandbox Code Playgroud)
在调用processQueue()之前避免双表单提交.
至于sendingmultiple,successmultiple并且errormultiple,你要什么都发生在那里?评论只是表明这些事件何时被触发.
我个人使用:
this.on('sendingmultiple', function () {
// `sendingmultiple` to hide the submit button
$('#my-dropzone').find('button[type=submit]').hide();
});
this.on('successmultiple', function (files, response) {
// `successmultiple` to reload the page (and show the updated info)
window.location.reload();
});
this.on('errormultiple', function (files, response) {
// `errormultiple` to un-hide the button
$('#my-dropzone').find('button[type=submit]').show();
});
Run Code Online (Sandbox Code Playgroud)
但是你当然可以做你想做的事.
最后,你打算在<script>标签的最后一行发生什么?我不太明白,看起来如果你想在成功时重新处理队列.它似乎不属于那里.
评论是否有任何关闭,但这个设置对我来说很好.
| 归档时间: |
|
| 查看次数: |
4846 次 |
| 最近记录: |