1. 先设置好文件的获取地址,在settings中设置
# 指定文件获取的url路径
MEDIA_URL = 'file/image/'
2.根据设置好获取文件的地址配置路由
urlpatterns = [
# 获取头像的路由
re_path(r'file/image/(.+?)/', FileView.as_view())
]
3.视图函数,这里直接继承APIView就好了
class FileView(APIView):
def get(self, request, name):
# 1. 获取路径
path = MEDIA_ROOT / name
# 2. 判断文件存不存在
if os.path.isfile(path):
# 3. 存在的话使用Django内置的文件响应去打开文件
return FileResponse(open(path, 'rb'))
# 4. 不存在的话给出提示
return Response({'error': '没有找到该文件!'}, status=status.HTTP_404_NOT_FOUND)