我正在努力与Flask和上传文件,到目前为止我的Flask代码:
@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添加任何文件,请求将失败并抛出异常。我不知道为什么。
答案 0 :(得分:0)
我认为你应该写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。