【Python Fastapi】js上传文件,fastapi处理,js显示回传信息

【Python Fastapi】js上传文件,fastapi处理,js显示回传信息_第1张图片

python

from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from typing import List
import requests

app = FastAPI()

# 配置静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")


# HTML页面路由
@app.get("/", response_class=HTMLResponse)
async def get_upload_page():
    return """
    
    
    
        Image Upload
    
    
        

Image Upload

"""
# 文件上传端点 @app.post("/upload") async def file_(file: bytes = File(...)): # 如果要上传多个文件 files: List[bytes] = File(...) """使用File类 文件内容会以bytes的形式读入内存 适合于上传小文件""" return {"file_size": len(file)} # 返回文件大小 if __name__ == "__main__": import uvicorn uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True, workers=1)

js

document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('form');
  const fileInput = document.querySelector('input[type="file"]');
  const descriptions = document.getElementById('descriptions');

  form.addEventListener('submit', async (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);

    try {
      const response = await fetch('/upload', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        descriptions.innerHTML = `File size: ${data.file_size} bytes`;
      } else {
        descriptions.innerHTML = 'Upload failed';
      }
    } catch (error) {
      console.error('Error:', error);
      descriptions.innerHTML = 'An error occurred';
    }
  });
});

结果网页:
【Python Fastapi】js上传文件,fastapi处理,js显示回传信息_第2张图片

你可能感兴趣的:(Python语言,python,fastapi,javascript)