Django - 在POST请求后将文件下载到客户端

时间:2014-09-17 16:45:35

标签: django python-2.7 file-upload django-forms

我是Django的新手,我正在处理一个可以上传xlsx文件的表单,服务器会对它进行一些操作,然后返回xlsx的编辑版本。现在,我只是测试一些基本的东西,所以我上传文件后想要做的就是返回我创建的CSV文件

事实是,我正在尝试返回新文件,但文件没有作为文件下载,它只是由服务器返回,你只能在“网络”标签中看到它,你可以看到有关您在浏览器中显示的页面的信息。

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>

为什么会发生这种情况,我该怎么做才能修复它?

谢谢:)

1 个答案:

答案 0 :(得分:0)

客户端发送csv文件的方法

def _download(path):
    if os.path.exists(path):
        with open(path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="text/csv", charset="utf-8")
            response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(path)
            return response
    raise Http404