我正在使用 Flask 上传文件。 为了防止同一个文件存储两次,我打算从文件内容中计算出 md5,并将文件存储为 .除非文件已经存在。
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
#next line causes exception
img_key = hashlib.md5(file).hexdigest()
不幸的是,hashlib.md5 抛出异常:
TypeError: must be string or buffer, not FileStorage
我已经尝试过 file.stream - 同样的效果。
有没有什么办法可以在不临时保存的情况下从文件中获取md5?
最佳答案
request.files['file']
属于 FileStorage
类型,它有一个 read()
方法。
尝试做:
file = request.files['file']
#file.read() is the same as file.stream.read()
img_key = hashlib.md5(file.read()).hexdigest()
关于 FileStorage
的更多信息:http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage
关于python - 从 werkzeug.datastructures.FileStorage 计算 md5 而不将对象保存为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24570066/