0.url
path('download_file/', views.download_file, name='download_file'),
1. view
def download_file(request):
"""
下载
"""
id = request.GET.get('id')
file_obj = models.MyFile.objects.filter(id=id).first()
# http://127.0.0.1:8000/media/book/book.txt
# http://127.0.0.1:8000/media/book/book.jpg # 现在:book/book.txt
url = 'http://127.0.0.1:8000' + file_obj.my_file.url
# url = 'https://t33-1305448189.cos.ap-nanjing.myqcloud.com/p333.jpg'
print(url)
# 大文件的下载
# data = requests.get(url).iter_content()
# 正常文件的下载
data = requests.get(url).content
# 弹框提示框
response = HttpResponse(data, content_type="application/octet-stream")
# 中文转义
from django.utils.encoding import escape_uri_path
# 设置下载头
# print(file_obj.my_file.url)
name = file_obj.my_file.url.split('/')[-1]
# print(name)
response['Content-Disposition'] = "attachment;filename={};".format(escape_uri_path(name))
return response
2.models.py
class MyFile(models.Model):
"""
文件下载
"""
name = models.CharField(verbose_name='名称', max_length=225)
my_file = models.FileField(upload_to="my_file", verbose_name="教程", default='my_file/my_file.txt')