传递图片数据时,后端发出的错误
这是前端vue的代码
<template>
<el-upload
class="upload-demo"
drag
action="#"
multiple
:file-list="fileList"
:http-request="handleUpload"
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">
Drop file here or <em>click to upload</em>
</div>
</el-upload>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { UploadFilled } from '@element-plus/icons-vue';
import axios from 'axios';
const fileList = ref<File[]>([]);
function handleUpload(files: FileList) {
const formData = new FormData()
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i], files[i].type);
}
axios.post('http://localhost:8000/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
// 'Content-Type': 'application/json'
}
})
.then(response => {
// 处理成功回调
})
.catch(error => {
console.error("上传失败:", error.message); // 输出错误消息
if (error.response) {
console.log(formData)
console.error("响应状态码:", error.response.status);
console.error("响应数据:", error.response.data);
} else if (error.request) {
console.error("请求异常,无响应:", error.request);
} else {
console.error("未知错误:", error.message);
}
})
}
</script>
这是后端fastapi的代码
from pathlib import Path
from typing import List
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.responses import JSONResponse
import os
import uvicorn
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import HTMLResponse, FileResponse, StreamingResponse
from starlette.staticfiles import StaticFiles
app = FastAPI(debug=True)
UPLOAD_FOLDER = "./data"
origins = [
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/api/upload")
async def upload_files(files: List[UploadFile] = File(...)):
# async def upload_files(file_info: FileWithMetadata):
# 保存文件到磁盘
# for file in FileWithMetadata:
data_folder = 'data'
if not os.path.exists(data_folder):
os.makedirs(data_folder)
for file in files:
file_path = os.path.join(data_folder, file.filename)
with open(file_path, "wb+") as f:
for line in file.file:
f.write(line)
return JSONResponse(status_code=200, content={"message": "Files uploaded successfully."})
if __name__ == '__main__':
uvicorn.run(app=app, host="localhost", port=8000)
请大佬们看看哪里出错了QAQ