百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

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

liuian 2025-04-06 18:08 17 浏览

最近构思实现了一个小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': '/'
        }
      }
    }
  }
})

相关推荐

GCI: Another key public good for international community

MembersofadelegationofhighschoolstudentsfromtheU.S.stateofWashingtonposeforaphotoa...

kube on kube 实现思路分享(kube-scheduler)

这里的kubeonkube,是指建立K8s元集群,纳管其他业务K8s集群,通过声明式API管理集群的创建、增删节点等。参考https://github.com/kubean-i...

China and India hold the key to a more inclusive global future

ByMayaMajueranLead:AsChinaandIndiamark75yearsofdiplomaticties,theircooperationcouldse...

日本真子公主的婚礼又要提上日程了吗?未婚夫:债务问题已解决

日本明仁天皇将于今年3月31日退位,德仁皇太子即将成为新一任的天皇。在平成时代最后的倒计时中,明仁天皇的孙女真子公主的婚事却又一次进入了人们的视野。(viaTheTelegraph)关注日本皇室的...

kratos源码分析系列(1)(kvm源码解析与应用 pdf)

https://github.com/go-kratos/kratos是b站开源的一个微服务框架,整体来看它结合grpc生态中的grpc-gateway,以及wire依赖注入和众多常用的trace,m...

【2.C#基础】6.循环语句(c#循环语句例子)

6.循环语句当需要多次执行同一个处理时,就需要用到循环语句。一般情况下,循环的流程图如下:6.1while循环C#中的while循环语句在给定的条件为真的情况下会重复执行目标语句。格式如下:...

使用 Google Wire 在 Go 中进行依赖注入

关注点分离、松耦合系统和依赖反转原则等概念在软件工程中是众所周知的,并且在创建良好的计算机程序过程中至关重要。在本文中,我们将讨论一个同时应用了这三个原则的技术,称为依赖注入。我们将尽可能地实践,更加...

用 Golang封装你的API(golang封装dll)
用 Golang封装你的API(golang封装dll)

每日分享最新,最流行的软件开发知识与最新行业趋势,希望大家能够一键三连,多多支持,跪求关注,点赞,留言。@头条创作挑战赛本文探讨了在用Golang封装你的API的过程以及几个不同的编程步骤。我做了一个非常有限的时间来证明如何为客户正在开...

2025-05-09 20:03 liuian

Terraform 实战 | 万字长文(terrify是什么意思中文)

Terraform是什么Terraform(https://www.terraform.io/)是HashiCorp旗下的一款开源(Go语言开发)的DevOps基础架构资源管理运维工具,可...

Go 语言入门:环境安装(go语言安装 window)

一、前言这里不同于其他人的Go语言入门,环境安装我向来注重配置,比如依赖包、缓存的默认目录。因为前期不弄好,后面要整理又影响这影响那的,所以就干脆写成文章,方便后期捡起。二、安装1.安装包htt...

Go语言进阶之Go语言高性能Web框架Iris项目实战-项目结构优化EP05

前文再续,上一回我们完成了用户管理模块的CURD(增删改查)功能,功能层面,无甚大观,但有一个结构性的缺陷显而易见,那就是项目结构过度耦合,项目的耦合性(Coupling),也叫耦合度,进而言之,模块...

如何将Go项目与Docker结合实现高效部署

在现代软件开发中,使用Docker部署应用程序已经成为一种标准实践。本文将深入探讨如何将Go项目与Docker结合,实现高效、可靠的部署过程。通过详细的步骤和丰富的示例,你将能够迅速掌握这一流程。准备...

五分钟轻松熟悉一个k8s Operator应用制作

简介:operator是一种kubernetes的扩展形式,可以帮助用户以Kubernetes的声明式API风格自定义来管理应用及服务,operator已经成为分布式应用在k8s集群部...

程序员的副业秘籍!一款可以快速搭建各类系统的后台管理系统

系统简介这是一个基于Gin+Vue+ElementUI(或ArcoDesign、AntDesign)的系统快速开发平台,采用了前后端分离,旨在帮助用户快速完成各类系统的基础功能搭建。平...

使用 Go 语言开发区块链钱包的项目目录结构设计

在开发区块链钱包时,项目的目录结构应该清晰、模块化,确保代码的可维护性和扩展性。基于Go的惯例,结合区块链钱包的功能需求,以下是一个较为合理的目录结构示例:1.目录结构blockchain-wa...