网站首页 > 技术文章 正文
最近构思实现了一个小demo网站,前端上传文件,后端分析文件,最后前端展示,整个过程还是蛮有意思的,刚刚开始学习网站开发,还有很多不会的地方,这里演示fastapi+vue3文件上传,上传的excel文件直接存入mongo中,读也是从mongo中读。
后台代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/1/19 09:20
# @Author : ailx10
# @File : main.py
# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
from pymongo import MongoClient
import io
from fastapi import File, UploadFile
from fastapi.responses import JSONResponse
app = FastAPI()
# CORS 设置,允许所有来源访问,生产环境时应根据需要进行调整
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
client = MongoClient("mongodb://admin:passwd@localhost:27017/")
db = client.alarm_analysis
collection = db.raw_sample
@app.get("/get_samples/{page}")
async def get_samples(page: int):
skip = (page - 1) * 10
samples = collection.find().skip(skip).limit(10)
# 转换 ObjectId 为字符串
samples = [{**sample, "_id": str(sample["_id"])} for sample in samples]
total_samples = collection.count_documents({}) # 获取总样本数
return JSONResponse(content={"data": samples, "total": total_samples})
@app.post("/upload_excel")
async def upload_excel(file: UploadFile = File(...)):
contents = await file.read()
df = pd.read_excel(io.BytesIO(contents))
samples = df.to_dict(orient="records")
result = collection.insert_many(samples)
return {"inserted_ids": [str(id) for id in result.inserted_ids]}
前端代码:
// HelloWorld.vue
<template>
<div>
<h1>Alarm Analysis</h1>
<input type="file" @change="uploadExcel" />
<table v-if="samples.length > 0">
<thead>
<tr>
<th v-for="key in filteredKeys" :key="key">{{ key }}</th>
</tr>
</thead>
<tbody>
<tr v-for="sample in samples" :key="sample._id">
<td v-for="key in filteredKeys" :key="key">{{ sample[key] }}</td>
</tr>
</tbody>
</table>
<div>
<button @click="prevPage" :disabled="page === 1">上一页</button>
<label for="currentPage">当前页:</label>
<input type="number" id="currentPage" v-model="page" @input="validatePage" min="1" :max="totalPage" />
<button @click="nextPage" :disabled="page === totalPage">下一页</button>
<button @click="loadSamples">跳转</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
samples: [],
page: 1,
totalPage: 1,
};
},
mounted() {
this.loadSamples();
},
computed: {
filteredKeys() {
// 获取样本的键,排除 _id 和 sheet
return Object.keys(this.samples[0] || {}).filter(key => key !== '_id' && key !== 'sheet');
},
},
methods: {
async uploadExcel(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
// 使用代理配置的URL
await axios.post('/api/upload_excel', formData);
// 重新加载样本数据
this.page = 1;
this.samples = [];
this.loadSamples();
},
async loadSamples() {
const response = await axios.get(`/api/get_samples/${this.page}`);
this.samples = response.data.data;
// 计算总页数,假设每页显示10行
this.totalPage = Math.ceil(response.data.total / 10);
},
validatePage() {
// 确保输入页码在有效范围内
if (this.page < 1) {
this.page = 1;
} else if (this.page > this.totalPage) {
this.page = this.totalPage;
}
},
prevPage() {
if (this.page > 1) {
this.page -= 1;
this.loadSamples();
}
},
nextPage() {
if (this.page < this.totalPage) {
this.page += 1;
this.loadSamples();
}
},
},
};
</script>
代理配置:
// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
open:true,
host:'localhost',
port:8080,
https:false,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}
}
}
})
猜你喜欢
- 2025-06-12 比较常见类型漏洞讲解(二):文件上传
- 2025-06-12 文件上传漏洞全面渗透姿势总结(文件上传漏洞的防御主要从以下几个方面考虑)
- 2025-06-12 Selenium上传文件有多少种方式?不信你有我全
- 2025-06-12 Spring Boot超大文件上传的正确方式
- 2025-06-12 文件太大上传不了?看这里,秒传(文件太大传不过去)
- 2025-06-12 前端开发-文件上传,如何使用XMLHttpRequest将文件发送到后台?
- 2025-06-12 前端移动端上传图片pc端如何实时获取
- 2024-10-03 .NET Core WebAPI 基础文件上传 winform调用webapi上传文件
- 2024-10-03 SpringBoot中实现文件上传下载的三种解决方案(推荐)
- 2024-10-03 SPRING BOOT实现文件上传和下载 spring boot 上传文件 路径
你 发表评论:
欢迎- 513℃几个Oracle空值处理函数 oracle处理null值的函数
- 512℃Oracle分析函数之Lag和Lead()使用
- 504℃Oracle数据库的单、多行函数 oracle执行多个sql语句
- 499℃0497-如何将Kerberos的CDH6.1从Oracle JDK 1.8迁移至OpenJDK 1.8
- 490℃Oracle 12c PDB迁移(一) oracle迁移到oceanbase
- 483℃【数据统计分析】详解Oracle分组函数之CUBE
- 464℃Oracle有哪些常见的函数? oracle中常用的函数
- 463℃最佳实践 | 提效 47 倍,制造业生产 Oracle 迁移替换
- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端react (48)
- 前端aes加密 (58)
- 前端脚手架 (56)
- 前端md5加密 (54)
- 前端富文本编辑器 (47)
- 前端路由 (61)
- 前端数组 (73)
- 前端排序 (47)
- 前端定时器 (47)
- Oracle RAC (73)
- oracle恢复 (76)
- oracle 删除表 (48)
- oracle 用户名 (74)
- oracle 工具 (55)
- oracle 内存 (50)
- oracle 导出表 (57)
- oracle 中文 (51)
- oracle的函数 (57)
- 前端调试 (52)
- 前端登录页面 (48)
本文暂时没有评论,来添加一个吧(●'◡'●)