1:项目根目录存放图片的目录
2:settings.py 添加
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
3:url.py 添加后面路径自己定义
import django.views.static
url(r'^media/(?P.*)',django.views.static.serve,{'document_root':'C:\Users\Administrator\PycharmProjects\itracnew\itrac\media'}),
4:views.py
from xxx import settings
def test(request): if request.method =="POST": f1 = request.FILES['pic'] fname = '%s/%s' % (settings.MEDIA_ROOT, f1.name) picname = fname.split(".")[0]+".png" with open(picname, 'wb') as pic: for c in f1.chunks(): pic.write(c) print("picture OK",picname) post_pic = str(picname.split("/")[1])
5:html文件
上传图片(可选):
6:我在models文件加了一个字段方便存名字调用
pict = models.CharField(max_length=100,null=True,blank=True)