我正在使用Flask micro-framework 0.6和Python 2.6
我需要从上传的文件中获取mimetype,以便我可以存储它。
以下是相关的Python / Flask代码:
@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
mimetype = #FIXME
if file:
file.save(os.path.join(UPLOAD_FOLDER, 'File-Name')
return redirect(url_for('uploaded_file'))
else:
return redirect(url_for('upload'))
这是网页的代码:
<form action="upload_file" method=post enctype=multipart/form-data>
Select file to upload: <input type=file name=file>
<input type=submit value=Upload>
</form>
代码有效,但我需要能够在上传时获取mimetype。我在这里看过Flask文档:http://flask.pocoo.org/docs/api/#incoming-request-data
所以我知道它确实得到了mimetype,但我无法弄清楚如何检索它 - 作为文本字符串,例如'TXT /纯'。
有什么想法吗?
谢谢。
答案 0 :(得分:23)
从docs开始,file.content_type
包含带编码的完整类型,mimetype
仅包含mime类型。
@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files.get('file')
if file:
mimetype = file.content_type
filename = werkzeug.secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER, filename)
return redirect(url_for('uploaded_file'))
else:
return redirect(url_for('upload'))
答案 1 :(得分:2)
理论上您可以使用request.files['YOUR_FILE_KEY'].content_type
,但是该实现(包括在werkzeug.datastructures中)可以信任客户端提供的内容,也可以使用mimetypes.guess_type
来仅检查文件扩展名(请参阅Python文档here)。
class FileMultiDict(MultiDict):
"""A special :class:`MultiDict` that has convenience methods to add
files to it. This is used for :class:`EnvironBuilder` and generally
useful for unittesting.
.. versionadded:: 0.5
"""
def add_file(self, name, file, filename=None, content_type=None):
"""Adds a new file to the dict. `file` can be a file name or
a :class:`file`-like or a :class:`FileStorage` object.
:param name: the name of the field.
:param file: a filename or :class:`file`-like object
:param filename: an optional filename
:param content_type: an optional content type
"""
if isinstance(file, FileStorage):
value = file
else:
if isinstance(file, string_types):
if filename is None:
filename = file
file = open(file, 'rb')
if filename and content_type is None:
content_type = mimetypes.guess_type(filename)[0] or \
'application/octet-stream'
value = FileStorage(file, filename, name, content_type)
self.add(name, value)
根据您的用例,您可能希望使用python-magic,它将使用实际文件来获取mimetype。会是这样的:
import magic
def get_mimetype(data: bytes) -> str:
"""Get the mimetype from file data."""
f = magic.Magic(mime=True)
return f.from_buffer(data)
get_mimetype(request.files['YOUR_FILE_KEY'].stream.read(MAX_LENGTH))