簡體   English   中英

如何處理 flask 中的圖像上傳?

[英]how to deal with image upload in flask?

I am developing an API in flask, and a feature that supports the API, is uploading an avatar image, in order to do this I read the img as base64 and I send the base64 code of the img to the backend.

這個app.config["MAX_CONTENT_LENGTH"] = 0.1 * 1024 * 1024不起作用,我將圖像發送到服務器的時間過長。

問題是我可以使用哪些最佳實踐來使端點能夠上傳照片。

base64 是正確的選擇嗎? 我需要在后端壓縮 img 嗎?

謝謝

這是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 the user does not select a file, the browser submits an
        # empty file without a 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('download_file', name=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>
    '''

從中修改/改進應該是相當容易的。

OP評論后編輯
您可以使用我發送的文檔鏈接的改進上傳部分中包含的建議來限制上傳大小。

為了簡單起見,我還在這里粘貼了示例:

from flask import Flask, Request

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000

如果它對您不起作用,並且您想要關於該主題的答案,請縮小問題范圍。

在任何情況下,我都會提供一個指針:您是否在初始化應用程序后立即設置了 app.config['MAX_CONTENT_LENGTH'](如示例中所示)?

關於不保留上傳文件名,您可以以任何您喜歡自定義此部分的方式更改它:

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('download_file', name=filename))

閱讀您的評論,我假設您指出 API 永遠不應信任用戶輸入這一事實,因此在文檔中還提到了以下內容:

那么 secure_filename() function 實際上是做什么的呢? 現在的問題是有一個原則叫做“從不相信用戶輸入”。 上傳文件的文件名也是如此。 所有提交的表單數據都可能被偽造,文件名可能很危險。 目前只需要記住:在將文件名直接存儲到文件系統之前,始終使用 function 來保護文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM