网站首页 > 技术文章 正文
最近构思实现了一个小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': '/'
}
}
}
}
})
猜你喜欢
- 2024-11-17 从零开始构建PDF阅读器(最简单的pdf阅读器)
- 2024-11-17 Dooring可视化之从零实现动态表单设计器
- 2024-11-17 在 FastAPI 中处理表单和用户输入:综合指南
- 2024-11-17 Laravel9表单的验证(validate表单验证)
- 2024-11-17 第63节 Form表单-Web前端开发之JavaScript-王唯
- 2024-11-17 Gateway结合Sentinel1.8限流熔断及自定义异常
- 2024-11-17 手机网站常见问题总结(手机网站出现错误怎么办)
- 2024-11-17 CSS实现去除Input框默认样式的详细教程
- 2024-11-17 企业必备实战之Sentinel规则Nacos持久化
- 2024-11-17 禁用qq浏览器数字文本框 鼠标滚轮滑动 数字加减
- 标签列表
-
- content-disposition (47)
- nth-child (56)
- math.pow (44)
- 原型和原型链 (63)
- canvas mdn (36)
- css @media (49)
- promise mdn (39)
- readasdataurl (52)
- if-modified-since (49)
- css ::after (50)
- border-image-slice (40)
- flex mdn (37)
- .join (41)
- function.apply (60)
- input type number (64)
- weakmap (62)
- js arguments (45)
- js delete方法 (61)
- blob type (44)
- math.max.apply (51)
- js (44)
- firefox 3 (47)
- cssbox-sizing (52)
- js删除 (49)
- js for continue (56)
- 最新留言
-