编程技术文章分享与教程

网站首页 > 技术文章 正文

fastapi+vue3文件上传(vue ftp上传)

hmc789 2024-11-17 11:23:05 技术文章 2 ℃

最近构思实现了一个小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': '/'
        }
      }
    }
  }
})
标签列表
最新留言