python
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from typing import List
import requestsapp = FastAPI()# 配置静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")# HTML页面路由
@app.get("/", response_class=HTMLResponse)
async def get_upload_page():return """<!DOCTYPE html><html><head><title>Image Upload</title></head><body><h1>Image Upload</h1><form method="post" enctype="multipart/form-data"><input type="file" name="file"><button type="submit">Upload</button></form><div id="descriptions"></div><script src="/static/main.js"></script></body></html>"""# 文件上传端点
@app.post("/upload")
async def file_(file: bytes = File(...)): # 如果要上传多个文件 files: List[bytes] = File(...)"""使用File类 文件内容会以bytes的形式读入内存 适合于上传小文件"""return {"file_size": len(file)} # 返回文件大小if __name__ == "__main__":import uvicornuvicorn.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';}});
});
结果网页: