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

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

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

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

相关推荐

Python生态下的微服务框架FastAPI

FastAPI是什么FastAPI是一个用于构建API的web框架,使用Python并基于标准的Python类型提示。与flask相比有什么优势高性能:得益于uvloop,可达到与...

SpringBoot:如何解决跨域问题,详细方案和示例代码

跨域问题在前端开发中经常会遇到,特别是在使用SpringBoot框架进行后端开发时。解决跨域问题的方法有很多,我将为你提供一种详细的方案,包含示例代码。首先,让我们了解一下什么是跨域问题。跨域是指在...

使用Nginx轻松搞定跨域问题_使用nginx轻松搞定跨域问题的方法

跨域问题(Cross-OriginResourceSharing,简称CORS)是由浏览器的同源策略引起的。同源策略指的是浏览器限制来自不同源(协议、域名、端口)的JavaScript对资源的...

spring boot过滤器与拦截器的区别

有小伙伴使用springboot开发多年,但是对于过滤器和拦截器的主要区别依然傻傻分不清。今天就对这两个概念做一个全面的盘点。定义与作用范围过滤器(Filter):过滤器是一种可以动态地拦截、处理和...

nginx如何配置跨域_nginx配置跨域访问

要在Nginx中配置跨域,可以使用add_header指令来添加Access-Control-Allow-*头信息,如下所示:location/api{if($reques...

解决跨域问题的8种方法,含网关、Nginx和SpringBoot~

跨域问题是浏览器为了保护用户的信息安全,实施了同源策略(Same-OriginPolicy),即只允许页面请求同源(相同协议、域名和端口)的资源,当JavaScript发起的请求跨越了同源策略,...

图解CORS_图解数学

CORS的全称是Cross-originresourcesharing,中文名称是跨域资源共享,是一种让受限资源能够被其他域名的页面访问的一种机制。下图描述了CORS机制。一、源(Orig...

CORS 幕后实际工作原理_cors的工作原理

跨域资源共享(CORS)是Web浏览器实施的一项重要安全机制,用于保护用户免受潜在恶意脚本的攻击。然而,这也是开发人员(尤其是Web开发新手)感到沮丧的常见原因。小编在此将向大家解释它存在...

群晖无法拉取Docker镜像?最稳定的方法:搭建自己的加速服务!

因为未知的原因,国内的各大DockerHub镜像服务器无法使用,导致在使用群晖时无法拉取镜像构建容器。网上大部分的镜像加速服务都是通过Cloudflare(CF)搭建的,为什么都选它呢?因为...

Sa-Token v1.42.0 发布,新增 API Key、TOTP 验证码等能力

Sa-Token是一款免费、开源的轻量级Java权限认证框架,主要解决:登录认证、权限认证、单点登录、OAuth2.0、微服务网关鉴权等一系列权限相关问题。目前最新版本v1.42.0已...

NGINX常规CORS错误解决方案_nginx配置cors

CORS错误CORS(Cross-OriginResourceSharing,跨源资源共享)是一种机制,它使用额外的HTTP头部来告诉浏览器允许一个网页运行的脚本从不同于它自身来源的服务器上请求资...

Spring Boot跨域问题终极解决方案:3种方案彻底告别CORS错误

引言"接口调不通?前端同事又双叒叕在吼跨域了!""明明Postman能通,浏览器却报OPTIONS403?""生产环境跨域配置突然失效,凌晨3点被夺命连环Ca...

SpringBoot 项目处理跨域的四种技巧

上周帮一家公司优化代码时,顺手把跨域的问题解决了,这篇文章,我们聊聊SpringBoot项目处理跨域的四种技巧。1什么是跨域我们先看下一个典型的网站的地址:同源是指:协议、域名、端口号完全相...

Spring Cloud入门看这一篇就够了_spring cloud使用教程

SpringCloud微服务架构演进单体架构垂直拆分分布式SOA面向服务架构微服务架构服务调用方式:RPC,早期的webservice,现在热门的dubbo,都是RPC的典型代表HTTP,HttpCl...

前端程序员:如何用javascript开发一款在线IDE?

前言3年前在AWSre:Invent大会上AWS宣布推出Cloud9,用于在云端编写、运行和调试代码,它可以直接运行在浏览器中,也就是传说中的WebIDE。3年后的今天随着国内云计算的发...