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