简单的记录下搭建网站时用到的图片上传与下载
settings中配置文件路径
# global_settings # 指定上传文件的存储路径(相对路径,用于读取文件) MEDIA_URL = '/media/' # 指定上传文件的存储路径(绝对路径,用于存储文件) MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls
from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), url(r'^student/',include('stu.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
子 urls
#coding=utf-8 from django.conf.urls import url from stu import views urlpatterns=[ url(r'^$',views.index_vies), url(r'^upload/$',views.upload), url(r'^show/$',views.show), url(r'^download/$',views.download) ]
templates
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/student/upload/" method="POST" enctype="multipart/form-data"> <p>姓名:<input type="text" name="username"/></p> <p>头像:<input type="file" name="photo"/></p> <p>   <input type="submit" value="上传"/></p> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table width="300px" border="1" cellspacing="0"> <tr> <th>编号</th> <th>姓名</th> <th>头像</th> <th>操作</th> </tr> {% for stu in stus %} <tr> <td>{{ forloop.counter }}</td> <td>{{ stu.sname }}</td> <td><img style="width: 100px" height="100px" src="/media/{{ stu.photo }}"/></td> <td><a href="/student/download/?photo={{ stu.photo }}">下载</a></td> </tr> {% endfor %} </table> </body> </html>
models
from django.db import models class Student(models.Model): sno = models.AutoField(primary_key=True) sname = models.CharField(max_length=32) photo = models.ImageField(upload_to="imgs") def __str__(self): return u'Student:%s' % self.sname
views
from django.http import HttpResponse from django.shortcuts import render import os from stu.models import * # 原生方式上传图片 def index_vies(request): if request.method == "GET": return render(request, "index.html") else: name = request.POST.get("username") photo = request.FILES.get("photo") if not os.path.exists('static'): os.makedirs("static") with open(os.path.join(os.getcwd(), "static", photo.name), "wb") as fw: fw.write(photo.read()) return HttpResponse("上传成功") return None # Django上传图片 def upload(request): name = request.POST.get("username") photo = request.FILES.get("photo") # 数据入库 Student.objects.create(sname=name, photo=photo) return HttpResponse("上传成功") # 展示图片 def show(request): # 获取学生信息 stus = Student.objects.all() return render(request, "show.html", {"stus": stus}) # 下载图片 def download(request): # 获取文件存储位置 filepath = request.GET.get("photo")# 获取文件名 imgs/aa.png filename = filepath[filepath.rindex("/") + 1:]# 获取文件的绝对路径 path = os.path.join(os.getcwd(), "media", filepath.replace("/", "\\")) with open(path, "rb") as fr: response = HttpResponse(fr.read()) response["Content-Type"] = "image/png" response["Content-Disposition"] = "inline;filename=" + filename return response