我目前拥有二进制格式的图像以及图像的扩展名。我想使用flask将图像存储在文件夹中。我该怎么办?
图像格式。
image = {
'img_src': binary_format_of_image,
'ext': image_extension,
'id': image_id
}
答案 0 :(得分:0)
Flask通过您的Flask应用程序介绍了uploading files
该页面上的一种方法:
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload-my-image', methods=['POST'])
def upload_file():
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(ABSOLUTE_PATH_TO_YOUR_FOLDER, filename))
new_image = Image(
path=PATH_TO_YOUR_FOLDER,
filename=filename,
ext=filename.rsplit('.', 1)[1].lower()
)
# Save new_image model
return redirect(url_for('uploaded_file', filename=filename))
Flask request.files
使用的数据结构是FileStorage。
还要注意,<form>
标签必须标记为enctype=multipart/form-data
和<input type=file>