#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>