django-文件下载
2022/2/24 6:24:51
本文主要是介绍django-文件下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
文件下载HttpResponse
response = HttpResponse(content=流, content_type="文件的媒体类型") # 下载使用的 response["Content-Disposition"] = "attachment;filename=a.jpg" return response
- attachment : 以附件的形式显示数据 (下载
- inline : 在线预览 (图片)
模型中 FileField 的类型是 FieldFile
FieldFile 常见的两个方法
- open() : 以流的形式读文件,类似于 python中 open函数
- chunks() : 类似于 文件上传中将的 以块的形式读取文件
- read() : 一次性读
# 获取上传的 文件路由 resource_path = res.resource.name from mimetypes import MimeTypes # 通过文件名、猜测文件的媒体类型 content_type, encoding = MimeTypes().guess_type(resource_path) content_type = content_type if content_type is not None else 'application/x-msdownload' response= HttpResponse(content_type=content_type) # 进行文件的下载 for chunk in res.resource.chunks(): response.write(chunk) # quote 是对 路径进行中文转码 from urllib.parse import quote # 获取下载的文件名 filename = quote(f"{res.resource_name}.{res.ext}") # 设置文件下载、并设置下载的文件名 response["Content-Disposition"] = "attachment;filename=" + filename return response
文件下载FileResponse
# as_attachment = False : false代表在线预览, true 代表下载 # filename 设置下载的文件名 # streaming_content 设置 下载的内容,值必须拥有 read() 方法 # 如果 streaming_content 设置的内容没有 read() 方法,必须设置成 可迭代的对象 return FileResponse(as_attachment=False, filename="a.jpg", streaming_content=io.BytesIO(photo))
通过 /media/xxxx 获取上传的资源 (直接暴露了资源的位置)
这篇关于django-文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26解决google chrome helper 内存占用较高!
- 2024-04-01got an unexpected keyword argument
- 2024-03-30维多利亚的秘密 golang入坑系统
- 2024-03-29mongodb sort by date
- 2024-03-29go swagger
- 2024-03-25mongodb cdc
- 2024-03-25how to use go in vscode
- 2024-03-22mongooseserverselectionerror: connect econnrefused ::1:27017
- 2024-03-21pymongo insert_many
- 2024-03-18projection mongodb