MEDIA_ROOT = BASE_DIR / 'yourFiles'
class UploadFile(models.Model):
"""上传文件模型"""
file = models.FileField('文件', help_text='文件上传')
info = models.JSONField('文件信息', help_text='文件信息', default=list, null=True, blank=True)
class UploadFileViewSet(viewsets.ModelViewSet):
"""文件上传视图集"""
queryset = UploadFile.objects.all()
serializer_class = UploadFileSerializer
...
@action(['get'], detail=True)
def show(self, request, pk, *args, **kwargs):
# 获取对象
try:
instance = self.get_object()
# instance.file.size()
return FileResponse(instance.file.open(mode='rb'))
except:
return response.Response({'msg':'Not Found!'}, status=404)
调用接口返回图片文件:
在axios封装的api请求中新增:
// 查看图片
showImg(id){
return api.get(`/upload/${id}/show/`, {responseType:'blob'}) // 后端返回的是一张图片,这里一定要加responseType
},
注意这里一定要新增 {responseType:'blob'}。后端返回的是一个图片文件:
this.imageUrl = window.URL.createObjectURL(response.data);