django - 使用 Django 发送文件时出错 - 文件结果为空

标签 django python-3.x response httpresponse

这是我的views.py 文件:

from django.http import HttpResponse

def render(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    response['X-Sendfile'] = '/files/filename.pdf'
    # path relative to views.py
    return response

当我运行服务器并请求时

http://localhost:8080/somestring

我得到一个名为 somefilename.pdf 的空文件。我怀疑 render 中缺少一些关键部分。

根据我的理解,此应用程序的 views.py 之外的其他部分是正确的。

最佳答案

这是解决我问题的代码:

from django.http import HttpResponse
from wsgiref.util import FileWrapper

def render(request): 
    response = HttpResponse(FileWrapper(open('file.pdf', 'rb')), content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    return response

关于django - 使用 Django 发送文件时出错 - 文件结果为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106006/

相关文章:

python - 使用 factory_boy 和 Authtools 的 Django-Python Django 登录测试失败

android - Retrofit 2 Request适用于Postman,但不适用于App

python re,多个匹配组

python - 在Python中将列表转换为字典

javascript - 如何在 Python 中编写一系列 Promise?

http - 403响应可以吗?

php - 如何使用 php 发送服务器错误响应?

django 对原始搜索结果进行分页

django - 如何在 Django 中测试 "render to template"函数? (测试驱动)

python - Django 中的评论