Flask / Python. Get mimetype from uploaded file(烧瓶/Python.从上传的文件中获取 mimetype)
问题描述
我使用 Flask 微框架 0.6 和 Python 2.6
I am using Flask micro-framework 0.6 and Python 2.6
我需要从上传的文件中获取 mimetype 以便我可以存储它.
I need to get the mimetype from an uploaded file so I can store it.
这是相关的 Python/Flask 代码:
Here is the relevent Python/Flask code:
@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'))
这是网页的代码:
And here is the code for the webpage:
<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/普通'.
The code works, but I need to be able to get the mimetype when it uploads. I've had a look at the Flask docs here: http://flask.pocoo.org/docs/api/#incoming-request-data
So I know it does get the mimetype, but I can't work out how to retrieve it - as a text string, e.g. 'txt/plain'.
有什么想法吗?
谢谢.
推荐答案
来自 docs,file.content_type
包含带编码的完整类型,mimetype
只包含 mime 类型.
From the docs, file.content_type
contains the full type with encoding, mimetype
contains just the mime type.
@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'))
这篇关于烧瓶/Python.从上传的文件中获取 mimetype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!