iT邦幫忙

1

伸縮自如的Flask [day13] 檔案上傳

  • 分享至 

  • xImage
  •  

首先是上傳檔案,
可以先看一下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時,我們可以拒絕進行存儲的動作。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言