import os def upload(request): if request.method == ‘GET‘: #将图片显示到html页面 img_list = models.Img.objects.all() return render(request,‘upload.html‘,{‘img_list‘: img_list}) elif request.method == "POST": user = request.POST.get(‘user‘) fafafa = request.POST.get(‘fafafa‘) obj = request.FILES.get(‘fafafa‘) #上传的路径 file_path = os.path.join(‘static‘,‘upload‘,obj.name) f = open(file_path, ‘wb‘) for chunk in obj.chunks(): f.write(chunk) f.close() #将路径保存到数据库中 models.Img.objects.create(path=file_path) return redirect(‘/upload.html‘)
Html代码 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/upload.html" enctype="multipart/form-data"> <input type="text" name="user" /> <input type="file" name="fafafa" /> <input type="submit" value="提交" /> </form> <div> {% for item in img_list %} <img style="height: 200px;width: 200px;" src="/{{ item.path }}" /> {% endfor %} </div> </body> </html>
原文:https://www.cnblogs.com/wuzhibinsuib/p/12828640.html