javascript - How to upload a file from Vue frontend to FastAPI backend
问题描述
Vuejs Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="file-upload-list" class="container">
<div class="large-12 medium-12 small-12 cell">
<label>File
<input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
</label>
<button v-on:click="submitFile()">Submit</button>
</div>
</div>
<script>
var fileList = new Vue({
data(){
return {
file: ''
}
},
el: "#file-upload-list",
methods: {
/*
Submits the file to the server
*/
submitFile(){
/*
Initialize the form data
*/
let formData = new FormData();
/*
Add the form data we need to submit
*/
formData.append('file', this.file);
console.log(this.file);
var baseURL="http://127.0.0.1:8000"
/*
Make the request to the POST /single-file URL
*/
axios.post( baseURL+'/uploadfiles',
// formData,
{
headers: {
'Content-Type': 'multipart/form-data'
},
file:this.file
}
).then(function(){
console.log('SUCCESS!!');
})
.catch(function(){
console.log('FAILURE!!');
});
console.log(formData);
},
/*
Handles a change on the file upload
*/
handleFileUpload(){
this.file = this.$refs.file.files[0];
}
}
});
</script>
</body>
</html>
FastAPI code
@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
result=""
for file in files:
fpath = os.path.join(
STORAGE_PATH, f'{file.filename}'
)
async with aiofiles.open(fpath, 'wb') as f:
content = await file.read()
await f.write(content)
return {"message": "success"}
I am trying to upload a pdf file from vuejs to fastAPI. where pdf file will be saved in a particular location in fastAPI code mentioned. I have tested the fastapi code in postman and it works good and I also enabled cross-origin. I am new to vuejs and I don't know how to do form action functionality. Mainly I need to know HTTPFile transaction is happening in the vuejs
解决方案
推荐阅读
- java - 基于 Web 的项目的实例变量
- ruby-on-rails - Rails link_to 并将参数合并到现有参数中
- c# - 同一解决方案中的多个 VSTO 项目
- c++ - MTd Vs MDd - QT Creator 中的静态链接 win32 库
- intershop - 设置 Intershop 7.10 开发环境
- redirect - 在负载均衡器后面将 HTTP 重定向到 HTTPS
- docker - 当端口 8080 未打开时,Traefik 仪表板不显示
- apache-kafka - Compaction 在什么条件下开始在 Kafka 中处理?
- android - 如果过滤在子项目中没有返回任何测试,则不要失败测试
- linux - 如何在 Docker 中以普通用户的身份 bash?