django实现从数据库获取图片在前端显示并下载


#url设置
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
path('admin/', admin.site.urls),
path('student/', include('app01.urls')),
path('student/', include('app01.urls')),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

###view设置
def showall_view(request):
#读取所有信息
stus = Student.objects.all()
return render(request,'show.html',{'stus':stus})

def download_view(request):
#获取请求参数
photo = request.GET.get('photo','')
filename = photo[photo.rindex('/')+1:]
path = os.path.join(os.getcwd(),'media',photo.replace('/','\\'))
print(path)
#开启一个流
with open(path,'rb') as fr:
response = HttpResponse(fr.read())
response['Content-Type']='image/png'

return response

###前端设置
{% for stu in stus %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ stu.sname }}</td>
<td><img width="200px" src="{{MEDIA_URL}}{{ stu.photo }}" alt=""></td>
<td><a href="/student/download/?photo={{ stu.photo }}">下载</a></td>

</tr>



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM