百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

fastapi+vue3文件上传(vue文件上传功能)

ztj100 2025-03-19 18:44 7 浏览 0 评论

最近构思实现了一个小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



<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': '/'
        }
      }
    }
  }
})

相关推荐

使用 Pinia ORM 管理 Vue 中的状态

转载说明:原创不易,未经授权,谢绝任何形式的转载状态管理是构建任何Web应用程序的重要组成部分。虽然Vue提供了管理简单状态的技术,但随着应用程序复杂性的增加,处理状态可能变得更具挑战性。这就是为什么...

Vue3开发企业级音乐Web App 明星讲师带你学习大厂高质量代码

Vue3开发企业级音乐WebApp明星讲师带你学习大厂高质量代码下栽课》jzit.top/392/...

一篇文章说清 webpack、vite、vue-cli、create-vue 的区别

webpack、vite、vue-cli、create-vue这些都是什么?看着有点晕,不要怕,我们一起来分辨一下。...

超赞 vue2/3 可视化打印设计VuePluginPrint

今天来给大家推荐一款非常不错的Vue可拖拽打印设计器Hiprint。引入使用//main.js中引入安装import{hiPrintPlugin}from'vue-plugin-...

搭建Trae+Vue3的AI开发环境(vue3 ts开发)

从2024年2025年,不断的有各种AI工具会在自媒体中火起来,号称各种效率王炸,而在AI是否会替代打工人的话题中,程序员又首当其冲。...

如何在现有的Vue项目中嵌入 Blazor项目?

...

Vue中mixin怎么理解?(vue的mixins有什么用)

作者:qdmryt转发链接:https://mp.weixin.qq.com/s/JHF3oIGSTnRegpvE6GSZhg前言...

Vue脚手架安装,初始化项目,打包并用Tomcat和Nginx部署

1.创建Vue脚手架#1.在本地文件目录创建my-first-vue文件夹,安装vue-cli脚手架:npminstall-gvue-cli安装过程如下图所示:创建my-first-vue...

新手如何搭建个人网站(小白如何搭建个人网站)

ElementUl是饿了么前端团队推出的桌面端UI框架,具有是简洁、直观、强悍和低学习成本等优势,非常适合初学者使用。因此,本次项目使用ElementUI框架来完成个人博客的主体开发,欢迎大家讨论...

零基础入门vue开发(vue快速入门与实战开发)

上面一节我们已经成功的安装了nodejs,并且配置了npm的全局环境变量,那么这一节我们就来正式的安装vue-cli,然后在webstorm开发者工具里运行我们的vue项目。这一节有两种创建vue项目...

.net core集成vue(.net core集成vue3)

react、angular、vue你更熟悉哪个?下边这个是vue的。要求需要你的计算机安装有o.netcore2.0以上版本onode、webpack、vue-cli、vue(npm...

使用 Vue 脚手架,为什么要学 webpack?(一)

先问大家一个很简单的问题:vueinitwebpackprjectName与vuecreateprojectName有什么区别呢?它们是Vue-cli2和Vue-cli3创建...

vue 构建和部署(vue项目部署服务器)

普通的搭建方式(安装指令)安装Node.js检查node是否已安装,终端输入node-v会使用命令行(安装)npminstallvue-cli-首先安装vue-clivueinitwe...

Vue.js 环境配置(vue的环境搭建)

说明:node.js和vue.js的关系:Node.js是一个基于ChromeV8引擎的JavaScript运行时环境;类比:Java的jvm(虚拟机)...

vue项目完整搭建步骤(vuecli项目搭建)

简介为了让一些不太清楚搭建前端项目的小白,更快上手。今天我将一步一步带领你们进行前端项目的搭建。前端开发中需要用到框架,那vue作为三大框架主流之一,在工作中很常用。所以就以vue为例。...

取消回复欢迎 发表评论: