方法一: 使用HttpResonse
下面方法从url获取file_path, 打开文件,读取文件,然后通过HttpResponse方法输出。
import os from django.http import HttpResponse def file_download(request, file_path): # do something... with open(file_path) as f: c = f.read() return HttpResponse(c)
然而该方法有个问题,如果文件是个二进制文件,HttpResponse输出的将会是乱码。对于一些二进制文件(图片,pdf),我们更希望其直接作为附件下载。当文件下载到本机后,用户就可以用自己喜欢的程序(如Adobe)打开阅读文件了。这时我们可以对上述方法做出如下改进, 给response设置content_type和Content_Disposition。
import os from django.http import HttpResponse, Http404 def media_file_download(request, file_path): with open(file_path, 'rb') as f: try: response = HttpResponse(f) response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response except Exception: raise Http404
HttpResponse有个很大的弊端,其工作原理是先读取文件,载入内存,然后再输出。如果下载文件很大,该方法会占用很多内存。对于下载大文件,Django更推荐StreamingHttpResponse和FileResponse方法,这两个方法将下载文件分批(Chunks)写入用户本地磁盘,先不将它们载入服务器内存。
方法二: 使用SteamingHttpResonse
import os from django.http import HttpResponse, Http404, StreamingHttpResponse def stream_http_download(request, file_path): try: response = StreamingHttpResponse(open(file_path, 'rb')) response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response except Exception: raise Http404
方法三: 使用FileResonse
FileResponse方法是SteamingHttpResponse的子类,是小编我推荐的文件下载方法。如果我们给file_response_download加上@login_required装饰器,那么我们就可以实现用户需要先登录才能下载某些文件的功能了。
import os from django.http import HttpResponse, Http404, FileResponse def file_response_download1(request, file_path): try: response = FileResponse(open(file_path, 'rb')) response['content_type'] = "application/octet-stream" response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path) return response except Exception: raise Http404
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
Django,客户端,下载文件
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 群星《前途海量 电影原声专辑》[FLAC/分轨][227.78MB]
- 张信哲.1992-知道新曲与精丫巨石】【WAV+CUE】
- 王翠玲.1995-ANGEL【新艺宝】【WAV+CUE】
- 景冈山.1996-我的眼里只有你【大地唱片】【WAV+CUE】
- 群星《八戒 电影原声带》[320K/MP3][188.97MB]
- 群星《我的阿勒泰 影视原声带》[320K/MP3][139.47MB]
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[320K/MP3][148.91MB]
- 刘雅丽.2001-丽花皇后·EMI精选王【EMI百代】【FLAC分轨】
- 齐秦.1994-黄金十年1981-1990CHINA.TOUR.LIVE精丫上华】【WAV+CUE】
- 群星.2008-本色·百代音乐人创作专辑【EMI百代】【WAV+CUE】
- 群星.2001-同步过冬AVCD【环球】【WAV+CUE】
- 群星.2020-同步过冬2020冀待晴空【环球】【WAV+CUE】
- 沈雁.1986-四季(2012梦田复刻版)【白云唱片】【WAV+CUE】
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[FLAC/分轨][257.88MB]
- 《国语老歌 怀旧篇 3CD》[WAV/分轨][1.6GB]