【发布时间】:2014-11-11 19:32:19
【问题描述】:
我是 Django 新手,我正在开发一个表单,您可以在其中上传 xlsx 文件,服务器对其进行一些操作,然后返回您的 xlsx 的编辑版本。现在,我只是在测试一些基本的东西,所以我上传文件后要做的就是返回一个我创建的 CSV 文件
问题是,我正在尝试返回新文件,但该文件并未作为 aa 文件下载,它只是由服务器返回,您只能在“网络”选项卡中查看您在浏览器中所在页面的相关信息。
views.py:
def home(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
new_file = UploadFile(file = request.FILES['file'])
new_file.save()
response = HttpResponse(content_type = 'text/csv')
writer = csv.writer(response)
writer.writerow(['foo', 'bar', 'baz'])
writer.writerow(['"hello"', '"2"'])
response['Content-Disposition'] = 'attachment; filename="test.csv"'
return response
else:
form = UploadFileForm()
data = {'form': form}
return render_to_response('index2.html', data, context_instance=RequestContext(request))
index2.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Upload a file in Django 1.5 using Dropzone.js</title>
{% load staticfiles %}
<link href="{{ STATIC_URL }}dropzone.css" type="text/css" rel="stylesheet"/>
<link href="{{ STATIC_URL }}css/bootstrap.min.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<!-- IMPORTANT enctype attribute! -->
<form class="dropzone" id="myDropzone" action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
</form>
<button id="submit-all" class="btn btn-primary">
Submit all files
</button>
<script src="{{ STATIC_URL }}dropzone.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
<script type="text/javascript">
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue : false,
addRemoveLinks: true,
removedfile: function(file) {
var _ref;
console.log((_ref = file.previewElement) != null);
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
init : function() {
var submitButton = document.querySelector("#submit-all")
var myDropzone = this;
console.log(myDropzone);
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
// Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
};
</script>
</body>
</html>
为什么会发生这种情况,我该怎么做才能解决它?
谢谢:)
【问题讨论】:
-
所以我能看到的唯一问题是
response['Content-Disposition'] = "attachment; filename=test.csv",去掉引号 -
仍然不起作用,但如果我粘贴创建 HttpResponse 的部分而不是 render_to_response 部分或“else”部分,它可以工作
-
在将响应传递给 csv 写入器之前,您是否尝试过在响应上设置内容处置?
-
我没有,但我现在试过了,但它不起作用:(虽然这真的很奇怪,因为如果我把这段代码放在 if request.method 之外的任何地方=='POST',它确实有效
标签: django python-2.7 file-upload django-forms