def change_icon(): form = UploadForm() img_url = '' if form.validate_on_submit(): #获得后缀 suffix = os.path.splitext(form.icon.data.filename)[1] #拼接文件名 filename = random_string() + suffix #保存 photos.save(form.icon.data, name=filename) # 生成缩略图 pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename) #打开文件 img = Image.open(pathname) img.thumbnail((128, 128)) img.save(pathname) #如果用户头像不是默认,说明上传了头像 #如果更新了,则删除原来的 if current_user.icon != 'default.jpg': os.remove( os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], current_user.icon)) current_user.icon = filename db.session.add(current_user) flash("头像已经保存") return redirect(url_for('users.change_icon')) img_url = photos.url(current_user.icon) return render_template('user/change_icon.html', form=form, img_url=img_url)
def change_icon(): img_url = '' form = UploadForm() if form.validate_on_submit(): #获取文件后缀 suffix = os.path.splitext(form.icon.data.filename)[1] #随机文件名 拼接 filename = random_string() + suffix photos.save(form.icon.data, name=filename) pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename) img = Image.open(pathname) img.thumbnail((128, 128)) img.save(pathname) if current_user.icon != 'default.jpg': os.remove(current_app.config['UPLOADED_PHOTOS_DEST'], current_user.icon) current_user.icon = filename #将新上传的文件名 赋值给 用户的头像 db.session.add(current_user) #保存在数据库中 flash("头像上传成功") return redirect(url_for("users.change_icon")) img_url = photos.url(current_user.icon) return render_template('user/change_icon.html', form=form, img_url=img_url)
def uploads(photo): photo_name = photos.save(photo) photo_url = photos.url(photo_name) return jsonify({'photo_url': photo_url, 'photo_name': photo_name})