实现用户在客户端更改头像,上传头像图片,自动生成缩略图显示。
前端代码:注意 enctype="multipart/form-data"
<form enctype="multipart/form-data" method="POST" action="{% url 'users:avatar_upload'%}">{% csrf_token %} <input type="file" name="image"/> <div class="modal-body"> <div class="cutimgbox"> <div class="btn-box-cutimg"> <input type="submit" class="btn btn-xxlg btn-micv5 btn-block" value="submit" /> </div> </div> </div> </form>
前端效果:
#视图函数修改头像
from PIL import Image @login_required # @csrf_exempt def avatar_upload(request): if request.method == 'POST': username = request.user.username user = UserProfile.objects.get(username=username) if 'image' in request.FILES: image = request.FILES['image'] #缩略图 s_img = Image.open(image) s_img.thumbnail((80, 80), Image.ANTIALIAS) if not os.path.exists(mini_img_path): os.makedirs(mini_img_path) img_url = mini_img_path + '\' + username+ ".jpeg" s_img.save(img_url ) user.avatar_small_thumbnall= r'uploadsavatarminipic'+'\' +username+ ".jpeg" user.save() return render(request,'users/userinfo.html',locals())
更改效果: