流程
-
写自定义类下的函数
- 用method=[“post”,]才能访问
- 路径为类路径/自定义名(如:类路径/upload/)
-
写文件存储的逻辑
- 文件存储的方式
- 被类下的视图函数调用
一、自定义存储方式
from datetime import datetime
#获取配置变量settings(settings.变量名)
from django.conf import settings
import random
import os
import uuid
def get_file_name_random_date():
filename = datetime.now().strftime('%Y-%m-%d').replace('-','')
filename += str(random.randint(1000,9999))
return file_name
def update_file(file,path:str,type:int):
'''
提供文件上传参数
:param file:要上传的文件
:param path:提供的路径
:param type:文件名称命名方式
1. 时间随机值
2. uuid随机值
return返回值
'''
new_name = ""
if type ==1:
new_name = get_file_name_random_date()
elif type == 2:
new_name = uuid.uuid4().hex
file_name = settings.MEDIA_ROOT + os.path.sep + path + os.path.sep + new_name + os.path.splitext(file.name)[1]
#os.path.sep是路径拼接
#file.name是文件的名称(带后辍的)、用os.path.splitext(file.name)[1]取文件类型
try:
#打开文件写入
f = open(file_name,'wb')
#如果文件比较大,要分多次写入
for i in file.chunks():
f.write(i)
#注:要关闭文件
f.close()
return {'status':True,'data':new_name+os.path.splitext(file.name)[1]}
except Exception as e:
return {'status':False,'error':'文件写磁盘出现异常'}
二、自定义函数
要在对应的视图类中写自定义函数
from rest_framework.decorators import action
from rest_framework.response import Response
#methods=['post','get']是传递的方式,文件一般用post,get用于测试
#detail=ture时是要进如明细才可以。如:/path/id(数据pk)/updload/才可以上传
@action(methods=['post','get'],detail=False)
def upload(self,request,*args,**kwargs):
#接收文件
rev_file = request.FILES.get('file')
if not rev_file:
return Response("上传失败!")
res = myupload.update_file(rev_file,'images',2)
return Response(res)