我已经设置了使用 wtforms、flask_wtf 和 flask_uploads 库上传个人资料图片,这些库将文件上传到static
Flask 文件夹中的服务器。我想阻止用户上传多个个人资料图片,并希望删除他们的旧图片。我已使用 IF 语句成功检测到服务器上的文件,但无法弄清楚如何删除文件或简单地将文件移动到可以手动删除的另一个文件夹。
我已经尝试过 Python 函数os.remove()
,但总是收到指定文件不存在的错误。根据我所阅读的内容,您不能在 Flask 中使用这样的功能,因为服务器正在积极运行,它会与活动进程混淆。
处理这个问题的最佳主意是什么?我希望有一个库函数可以首先检查文件名是否正在使用中,然后覆盖文件,但在库文档中找不到任何内容。我认识到我可以将个人资料图片上传到 SQL 表到 BLOB 中,但读到这不是最佳解决方案。
让我知道您的建议是什么,以解决防止用户上传过多文件的问题!
到目前为止我所拥有的:
import os, sys
from flask import Flask, render_template, flash, request, url_for, redirect, session, send_file, send_from_directory
# WTForms
from wtforms import Form, BooleanField, TextField, PasswordField, SelectField, RadioField, TextAreaField, DateField, DateTimeField, StringField, validators
from wtforms.widgets import TextArea
from wtforms.validators import DataRequired
from flask_wtf import FlaskForm, RecaptchaField
from flask_wtf.file import FileField, FileRequired, FileAllowed
from werkzeug.utils import secure_filename
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from MySQLdb import escape_string as thwart
app = Flask(__name__)
#### PROFILE PIC UPLOAD ####
# Based after https://gist.github.com/greyli/81d7e5ae6c9baf7f6cdfbf64e8a7c037
# For uploading files
PROF_PIC_UPLOAD_FOLDER = 'static/user_info/prof_pic'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app) # set maximum file size, default is 16MB
class ProfilePictureForm(FlaskForm):
prof_pic = FileField(validators=[FileAllowed(photos, u'Image only!')])
@app.route('/profile_picture_upload/', methods=['GET','POST'])
def profile_picture_upload():
form = ProfilePictureForm()
cid = str(session['clientcid'])
first_name = session['first_name']
static_url = url_for('static', filename='user_info/prof_pic/')
default_prof_pic = 'http://localhost:5000/_uploads/photos/static/user_info/prof_pic/default.jpg'
user_prof_pic = cid+first_name+'.png'
if form.validate_on_submit():
filename = photos.save(form.prof_pic.data, folder=PROF_PIC_UPLOAD_FOLDER,name=cid+first_name+'.png')
file_url = photos.url(filename)
# Checks if the prof_pic is set yet. if set, then dont need to delete the old picture on the server
if session['prof_pic'] != 'http://localhost:5000/_uploads/photos/static/user_info/prof_pic/default.jpg':
#need to delete or move the old prof_pic if it was set! Prevents users from adding too many pictures
flash("You already have a file on the server!")
#If the user_prof_pic is there, then
session['prof_pic'] = file_url
c, conn = connection()
c.execute("UPDATE cpersonals SET prof_pic = %s WHERE cid = (%s)", (file_url, cid))
conn.commit()
c.close()
conn.close()
else:
file_url = None
return render_template('profile_picture_upload.html', form=form, file_url=file_url)