将图像上传到Flask服务器 [英] Uploading an image to Flask server
问题描述
我在Flask上苦苦挣扎并上传了文件,这是到目前为止的Flask代码:
I am struggling bit with Flask and uploading a file, here is my Flask code so far:
@app.route('/api/user/update/', methods=['PUT'])
@auth.login_required
def update_user():
# check if the post request has the file part
user = User.query.filter_by(id=g.user.id,deleted=0).first()
try:
if 'uname' in request.args:
user.username = request.args['uname']
if 'password' in request.args:
user.hash_password(request.args['password'])
if 'lname' in request.args:
user.lastname = request.args['lname']
if 'fname' in request.args:
user.firstname = request.args['fname']
if 'address' in request.args:
user.address = request.args['address']
if 'preferance1' in request.args:
user.pre1 = request.args['preferance1']
if 'preferance2' in request.args:
user.pre2 = request.args['preferance2']
if 'preferance3' in request.args:
user.pre3 = request.args['preferance3']
if 'file' in request.files:
file = request.files['file']
filename = secure_filename(file.filename)
filename.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#print(filename)
#print(url_for('upload_file', filename=filename))
user.image_filename = filename
user.image_url = url_for('upload_file', filename=filename)
db.session.commit()
except:
print("Error")
db.session.rollback()
db.session.flush()
return jsonify({'user':user.serialize})
如果我从Postman中添加了任何内容作为文件,则请求将失败并且将引发异常.我不确定为什么.
If I added anything as a file from Postman the request will failed and exception will be thrown. I am not sure why.
推荐答案
我认为您应该编写 file.save(os.path.join(app.config ['UPLOAD_FOLDER'],filename))
而不是 filename.save(os.path.join(app.config ['UPLOAD_FOLDER'],filename))
. file
是一个 File Storage
对象.而且 filename
只是一个str.
I think you should write file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
instead of filename.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
. The file
is a File Storage
object. And the filename
is only a str.
这篇关于将图像上传到Flask服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!