首先是上传档案,
可以先看一下Flask官网的范例:
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
确认只有那些附档名可以上传
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
确认有档案上传,并且from werkzeug.utils import secure_filename中的secure_filename可以检查档名及MIME Type,但是如果有中文字,有可能档案名称就会被吃掉不回传了。
再来介绍python-magic这个套件,它可以帮助我们检查还是stream状态的档案MIME Type。
安装方式:
linux
pip install python-magic
windows
pip install python-magic-bin==0.4.14
再来是使用方法:
import magic
audio_File= request.files.get('audio_File')
mime_type = magic.from_buffer(audio_File.stream.read(), mime=True)
print(mime_type)
所以,要是上传的档案不是我们想要的mime_type时,我们可以拒绝进行存储的动作。
<<: 3+4 个 Google 判断付费连结 (Paid Links) 的方法
>>: 全磁碟加密(Full Disk Encryption)
Q: 这是小精灵吗? A: 这是... 吃蛋的小家伙!(不知道有没有版权问题呢?) 本篇的灵感来自...
mock react-router 的 <Redirect /> 元件是可行的,但这个做...
接续昨天的追踪练习~ 我本来看六指渊的,但某些地方遇到了卡点 补充其他影片辅助:https://ww...
最近Windows Updata有列印问题KB5000802, 而我是用Chrome进1111人力银...
之前有提到EyeJack可以拿来做明信片,但EyeJack除了可以做明信片外,也很适合用来写日记,只...