Django(img上传)

先来看一个例子

---------img.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/img" method="post" enctype="multipart/form-data"> ######上传文件必须要有enctype="multipart/form-data#######
<input type="file" name="file"> <input type="submit" value="提交">
</form>
<div>
{% for item in get_path %}
<img src="\{{ item.path }}" alt="图标" style="width: 100px;height: 200px">
{% endfor %}
</div>
</body>
</html>

----------urls.py
path('img',views.img),


-----------views.py
def img(req):
if req.method=="POST":
file=req.FILES.get("file") ####接受文件要用FILES####
file_path=os.path.join("static","upload",file.name).replace("\\","/")
models.File.objects.create(path=file_path)
f=open(file_path,"wb") ####将得到的文件写在static文件下的upload文件下#####
for i in file.chunks(): ###chunks是将文件以字节形式###
f.write(i)
f.close()
return redirect("/img")
elif req.method=="GET":
get_path=models.File.objects.all()
print(get_path)
return render(req,"img.html",{"get_path":get_path})
 

例如上传文件1.jpg,那么这个图片的路径是static/upload/1.jpg,浏览器输入127.0.0.1:8000/static/upload/1.jpg是找不到图片的,因为浏览器的输入的url要通过Django中的urls.py文件为接口进行查询,此时urls.py中没有相应的路由。解决方法如下

1.在settings.py中添加以下代码:
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(__file__),'static') STATICFILES_DIRS = ( ('upload',os.path.join(STATIC_ROOT,'upload').replace('\\','/') ), )
2.urls.py中添加:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import staticfiles
最后添加:
urlpatterns += staticfiles_urlpatterns()
3.将upload文件添加到static(和templates文件同级目录)文件下
4.测试
<p><img src="/static/upload/1.jpg"  width="980" height="180"></p>  

猜你喜欢

转载自www.cnblogs.com/gaoyukun/p/9096078.html
IMG
今日推荐