烧瓶/ Python。从上传的文件获取mimetype [英] Flask / Python. Get mimetype from uploaded file
问题描述
我使用Flask的micro-framework 0.6和Python 2.6
我需要从上传的文件中获取mimetype,以便存储它。 b
$ b
以下是相关的Python / Flask代码:
@ app.route('/ upload_file',methods = ['GET','POST'])
def upload_file():
if request.method =='POST':$ b $ 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
选择要上传的文件:< 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'。
有什么想法?
谢谢。
从 docs , file.content_type
包含完整的编码类型, mimetype
contains只是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'))
I am using Flask micro-framework 0.6 and Python 2.6
I need to get the mimetype from an uploaded file so I can store it.
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>
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'.
Any ideas?
Thank you.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!