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