20

我正在使用 Flask 微框架 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/plain”。

有任何想法吗?

谢谢你。

4

2 回答 2

43

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'))
于 2010-08-10T10:41:02.567 回答
7

理论上你可以使用request.files['YOUR_FILE_KEY'].content_type,但实现(包括在下面,在werkzeug.datastructures中找到)要么信任客户端提供的任何内容,要么使用mimetypes.guess_type仅检查文件扩展名的使用(请参阅此处的 Python 文档)。

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))
于 2018-07-17T14:58:46.397 回答