Django Serve .XLSX文件并强制下载 [英] Django Serve .XLSX File and force download
问题描述
我当前正在使用openPYXL来在Django中打开模板文件
I'm currently using openPYXL in order to open a template file within Django
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, fileName)
username = request.user.username
workbook = load_workbook(file_path)
worksheet = workbook.active
然后编辑文件,并以其他名称保存(此方法工作正常,我可以打开创建的文件,其中包含所需的信息),但是,我正在努力为该文件提供服务的用户,我已经尝试了如下所示的各种技术
The file is then edited, and saved under a different name(This works fine, I can open the created file and it contains the information desired), however what I'm struggling with is serving this file to the user, I've tried various techniques such as shown below
workbook.save('EvalofSelf1.xlsx')
response = HttpResponse()
file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response['X-Sendfile'] = file_path
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'DownloadedEval'
所有这些文件均按请求提供文件,但文件不包含实际数据,文件大小为0kb并且无法打开,如何从Django项目目录中提供已创建的文件,并保留其中存储的所有信息?
All of which serve a file as requested, but the file contains no actual data, is 0kb in size and unopenable, how can I serve up the created file from my Django project directory, retaining all information stored within it?
推荐答案
您永远不会将文件内容放入响应中,因此自然是0字节. X-Sendfile
的目的完全不同-当您重定向到静态服务器时-无论如何都需要URL,而不是文件路径.
You're not ever putting the file contents into the response, so naturally it is 0 bytes. X-Sendfile
is for a completely different purpose - when you're redirecting to a static server - and needs a URL, not a file path, anyway.
file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response = HttpResponse(open(file_path, 'rb').read())
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=DownloadedEval.xlsx'
这篇关于Django Serve .XLSX文件并强制下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!