python
pythonfrom 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 """
<!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 uvicorn
uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True, workers=1)
js
jsdocument.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';
}
});
});
结果网页:
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!