如何用django的drf自写一个图片返回的视图,通过get方式访问即可查看?
路由
urlpatterns = [
path('uploads/<str:file_name>', other.ViewSourceView.as_view()),
]
视图
class ViewSourceView(APIView):
authentication_classes = []
def get(self, request, file_name):
file_path = os.path.join(存放图片的目录, file_name)
print('file_path', file_path)
try:
with open(file_path, 'rb') as f:
data = f.read()
except FileNotFoundError:
return HttpResponse('目标对象不存在')
return HttpResponse(data, content_type="image/png")
使用
比如你有一张图片girls.png位于项目uploads/文件夹下,浏览器只需要访问 http://ip:port/uploads/girls.png 即可查看到。(注意路由)

浙公网安备 33010602011771号