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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:烧瓶/Python.从上传的文件中获取 mimetype


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01