当前位置: 首页>编程语言>正文

如何在Python中接收前端POST上传的文件

现代Web应用中,文件上传是一个常见的需求。前端通过HTTP POST请求将文件发送到后端服务器,后端接收并处理这些文件。Python作为后端开发语言,结合一些Web框架,可以轻松实现文件上传功能。本文将介绍如何使用Flask和FastAPI这两个流行的Python Web框架来接收前端上传的文件,并提供多个实际案例。

1. 使用Flask接收上传文件

Flask是一个轻量级的Python Web框架,适合快速开发和原型设计。我们首先介绍如何使用Flask接收前端上传的文件。

案例1:基本文件上传

首先,我们需要安装Flask:

pip install Flask

然后,创建一个简单的Flask应用来接收文件上传:

from flask import Flask, request, redirect, url_for
import os

app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'

# 确保上传文件夹存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def index():
    return '''
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Upload File</title>
    </head>
    <body>
        <h1>Upload File</h1>
        <form method="POST" action="/upload" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="Upload">
        </form>
    </body>
    </html>
    '''

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return "No file part"
    file = request.files['file']
    if file.filename == '':
        return "No selected file"
    if file:
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        return f"File uploaded successfully: {file.filename}"

if __name__ == '__main__':
    app.run(debug=True)

案例2:文件类型和大小校验

为了确保上传的文件符合要求,我们可以添加文件类型和大小的验证。

from werkzeug.utils import secure_filename

ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16 MB

app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return "No file part"
    file = request.files['file']
    if file.filename == '':
        return "No selected file"
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)
        return f"File uploaded successfully: {filename}"
    else:
        return "File type not allowed or file too large"

2. 使用FastAPI接收上传文件

FastAPI是一个现代、快速的Web框架,适合构建高性能的API。使用FastAPI接收文件上传也非常简单。

安装FastAPI和Uvicorn

pip install fastapi uvicorn

案例1:基本文件上传

创建一个FastAPI应用来接收文件上传:

from fastapi import FastAPI, File, UploadFile
import os

app = FastAPI()
UPLOAD_FOLDER = 'uploads'

# 确保上传文件夹存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    filepath = os.path.join(UPLOAD_FOLDER, file.filename)
    with open(filepath, "wb") as buffer:
        buffer.write(await file.read())
    return {"filename": file.filename}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

案例2:文件类型和大小校验

在FastAPI中,我们可以使用Pydantic定义校验规则。

from fastapi import FastAPI, File, UploadFile, HTTPException
from pydantic import BaseModel
import os

app = FastAPI()
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16 MB

# 确保上传文件夹存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    if not allowed_file(file.filename):
        raise HTTPException(status_code=400, detail="File type not allowed")
    if len(await file.read()) > MAX_CONTENT_LENGTH:
        raise HTTPException(status_code=400, detail="File too large")
    filepath = os.path.join(UPLOAD_FOLDER, file.filename)
    with open(filepath, "wb") as buffer:
        buffer.write(await file.read())
    return {"filename": file.filename}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

结语

在Python中接收前端POST上传的文件可以使用多种框架来实现,Flask和FastAPI是其中的两个流行选择。本文介绍了如何使用这两个框架实现基本的文件上传功能,并进行了文件类型和大小的校验。希望这些案例能帮助你在实际项目中更好地处理文件上传需求。


https://www.xamrdz.com/lan/5aa1962552.html

相关文章: