Бэкенд-код:< /p>
Код: Выделить всё
@app.post("/file"):
async def upload_file(files: Annotated[list[bytes], File()]):
saved_files=[]
path="DocumentStorage"
for file in files:
file_path=os.path.join(path)
if not os.path.exists(file_path):
os.makedirs(file_path)
file_save=os.path.join(file_path,"text.txt") #just a dummy name
try:
with open(file_save,"wb") as f:
f.write(file)
return {"file_sizes": [len(file) for file in files],"filedata":{files[0]}}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error saving file : {str(e)}")
print(files[0])
return {"file_sizes": [len(file) for file in files],"filedata":{files[0]}}
Код: Выделить всё
Client
Upload the files here
Select the file
const uploadfile = async () => {
let url = "http://127.0.0.1:8000/file";
let file = document.querySelector("#file");
console.log(file.files);
let data = new FormData();
data.append("files", file.files[0]);
console.log(data.values().next());
try {
let response = await fetch(url, { method: "POST", body: data });
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
let json = await response.json();
console.log(json);
} catch (err) {
console.log(err);
}
};
Подробнее здесь: https://stackoverflow.com/questions/790 ... -a-file-fr