本文实例为大家分享了Django实现上传图片的具体代码,供大家参考,具体内容如下
1.设置存放上传的图片的文件夹
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
2.创建图片路径的表结构
models.py
# 存放图片的表
class Avatar(models.Model):
user = models.CharField(max_length=100)
photo = models.ImageField(upload_to='photos', default='avatar.jpg')
3.构建并实施迁移文件
python manage.py makemigrations
python manage.py migrate
4.添加路径
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('upload/', views.UpLoadInfo),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
5.写逻辑
在view.py
# 上传图片
def UpLoadInfo(request):
if request.method == 'POST':
# img = request.FILES.get('photo')
# user = request.FILES.get('photo').name
new_img = models.Avatar(
photo=request.FILES.get('photo'), # 拿到图片
user=request.FILES.get('photo').name # 拿到图片的名字
)
new_img.save() # 保存图片
return HttpResponse('上传成功!')
return render(request, 'upload.html')
6.添加html页面
文件夹templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input name="photo" type="file" >
<button id="upload" type="submit">上传头像</button>
</form>
</body>
</html>
7.效果
运行项目,进入upload查看
上传成功之后