文件保存的路径配置
import platformsystem = platform.system()# 获取当前系统类型if system == "Windows":# 测试环境MEDIA_ROOT = "F:/Download/media/"DOMAIN = "http://127.0.0.1/"elif system == "Linux":# 线上环境MEDIA_ROOT = "/mnt/media/"DOMAIN = "http://xxxx.com/"else:MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')DOMAIN = "http://127.0.0.1/"# print(MEDIA_ROOT)MEDIA_URL = '/media/'
一、文件上传
1,使用自带的FileSystemStorage类
简单功能实现
from django.views import Viewfrom django.core.files.storage import FileSystemStorageclass SingleMediaView(View):def post(self, request):file = request.FILES.get('file', None)# 保存上传的文件到指定的绝对目录fs = FileSystemStorage()real_path = settings.MEDIA_ROOT + format_filenamefs.save(real_path, file)return JsonResponse({"status": 200, "msg": "上传成功"})
2,使用open函数
from django.views import Viewclass SingleMediaView(View):def post(self, request):file = request.FILES.get('file', 'None') with open('path/file.txt', 'wb+') as destination:for chunk in file.chunks():destination.write(chunk)return JsonResponse({"status": 200, "msg": "上传成功"})
open函数的第一方法写具体保存文件的路径
二、下载文件
使用StreamingHttpResponse类
class DownloadFileView(View):"""文件下载"""def get(self, request):file_id = request.GET.get("file_id", None)# 文件idif file_id:media = Media.objects.get(id=file_id)# 查询数据库real_path = settings.MEDIA_ROOT + media.url# 获取文件路径# 使用StreamingHttpResponse进行大文件下载,不占内存def file_iterator(file_path, chunk_size=8192):with open(file_path, 'rb') as file:while True:data = file.read(chunk_size)if not data:breakyield datafile_format = media.formatresponse = StreamingHttpResponse(file_iterator(real_path))if media.type == 1:# 图片下载response['Content-Type'] = f'image/{file_format}'elif media.type == 2:# 视频下载response['Content-Type'] = f'video/{file_format}'elif media.type == 3:# 其他类型文件下载response['Content-Type'] = 'application/octet-stream'# 使用quote对下载的中文文件名进行url编码,否则在Content-Disposition里的filename无法正确识别encoded_string = quote(f'{media.title}.{file_format.lower()}')response['Content-Disposition'] = f'attachment; filename="{encoded_string}"'return response
为DownloadFileView类视图配置url后请求时就可以直接下载了