springboot + Vue前后端项目(第十一记)

news2024/10/6 6:05:52

项目实战第十一记

  • 1.写在前面
  • 2. 文件上传和下载后端
    • 2.1 数据库编写
    • 2.2 工具类CodeGenerator生成代码
      • 2.2.1 FileController
      • 2.2.2 application.yml
      • 2.2.3 拦截器InterceptorConfig 放行
  • 3 文件上传和下载前端
    • 3.1 File.vue页面编写
    • 3.2 路由配置
    • 3.3 Aside.vue
  • 最终效果图
  • 总结
  • 写在最后

1.写在前面

本篇主要讲解文件的上传和下载,进行前后端的实现

2. 文件上传和下载后端

2.1 数据库编写

CREATE TABLE `sys_file` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件名称',
  `type` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件类型',
  `size` bigint(20) DEFAULT NULL COMMENT '文件大小(kb)',
  `url` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '下载链接',
  `md5` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '文件md5',
  `is_delete` tinyint(1) DEFAULT '0' COMMENT '是否删除',
  `enable` tinyint(1) DEFAULT '0' COMMENT '是否禁用链接',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

2.2 工具类CodeGenerator生成代码

其他的正常生成,需要application.yml改动和controller编写。需要注意的是File在java中重名了,换成Files即可(其他名称也行)

2.2.1 FileController

package com.ppj.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ppj.entity.Files;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ppj.common.Result;

import com.ppj.service.IFileService;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ppj
 * @since 2024-05-21
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private IFileService fileService;

    @Value("${files.upload.path}")
    private String fileUploadPath;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Files file) {
        fileService.saveOrUpdate(file);
        return Result.success();
    }

    @DeleteMapping("/{fileIds}")
    public Result delete(@PathVariable Integer[] fileIds) {
        fileService.removeByIds(Arrays.asList(fileIds));
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(fileService.list());
    }


    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                           @RequestParam String name) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name);
//        queryWrapper.orderByDesc("id");
        return Result.success(fileService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }


    /**
     * 文件上传接口
     * @param file 前端传递过来的文件
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + fileUUID);
        // 判断配置的文件目录是否存在,若不存在则创建一个新的文件目录
        File parentFile = uploadFile.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }

        String url;
        // 获取文件的md5
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFileByMd5(md5);
        if (dbFiles != null) { // 文件已存在,直接返回数据库里的url
            url = dbFiles.getUrl();
        } else {  // 文件不存在才生成url,保存数据至数据库
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件,则不删除刚才上传的文件
            url = "http://localhost:9000/file/" + fileUUID;
            // 存储数据库
            Files saveFile = new Files();
            saveFile.setName(originalFilename);
            saveFile.setType(type);
            saveFile.setSize(size/1024);
            saveFile.setUrl(url);
            saveFile.setMd5(md5);
            fileService.saveOrUpdate(saveFile);
        }
        return url;
    }

    /**
     * 通过文件的md5查询文件
     * @param md5
     * @return
     */
    private Files getFileByMd5(String md5) {
        // 查询文件的md5是否存在
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        Files one = fileService.getOne(queryWrapper);
        return one != null ? one : null;
    }

    /**
     * 文件下载接口   http://localhost:9090/file/{fileUUID}
     * @param fileUUID
     * @param response
     * @throws IOException
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
    // 开启和禁用其实就是更新
    @PostMapping("/update")
    public Result changeEnable(@RequestBody Files files){
        return fileService.saveOrUpdate(files)?Result.success():Result.error();
    }

}

2.2.2 application.yml

# 上传文件大小
spring:
  servlet:
    multipart:
      max-file-size: 10MB

# 文件存储路径
files:
  upload:
    path: D:\实战项目\前后端分离\后台管理系统演示\files\

2.2.3 拦截器InterceptorConfig 放行

package com.ppj.config;

import com.ppj.config.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    // 添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("/**")  // 拦截所有请求,通过判断token是否合法来决定是否需要登录
                .excludePathPatterns("/user/login", "/user/register", "/*/export", "/*/import","/file/**",
                        "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/api", "/api-docs", "/api-docs/**")
                .excludePathPatterns( "/*/*.html", "/*/*.js", "/*/*.css", "/*/*.woff", "/*/*.ttf");  // 放行静态文件

    }

    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

}

重点

  • 为了避免存储重复的文件,使用md5作为文件唯一标识码
  • 上传时要生成并存储这个文件的url,便于后面的下载和预览等等

3 文件上传和下载前端

3.1 File.vue页面编写

<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
      <el-button class="ml-5" type="primary" @click="getList">搜索</el-button>
      <el-button type="warning" @click="resetQuery">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-upload action="http://localhost:9000/file/upload" :show-file-list="false" :on-success="handleFileUploadSuccess" style="display: inline-block">
        <el-button type="primary" class="ml-5">上传文件 <i class="el-icon-top"></i></el-button>
      </el-upload>
      <el-button type="danger" class="ml-5" :disabled="multiple" @click="handleDelete">批量删除 <i class="el-icon-remove-outline"></i></el-button>
    </div>
    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="文件名称"></el-table-column>
      <el-table-column prop="type" label="文件类型"></el-table-column>
      <el-table-column prop="size" label="文件大小(kb)"></el-table-column>
      <el-table-column label="下载">
        <template v-slot="scope">
          <el-button type="primary" @click="download(scope.row.url)">下载</el-button>
        </template>
      </el-table-column>
      <!-- el-switch回显问题 -->
      <el-table-column label="启用">
        <template v-slot="scope">
          <el-switch v-model="scope.row.enable"
                     :active-value="1"
                     :inactive-value="0"
                     active-color="#13ce66" inactive-color="#ccc" @change="changeEnable(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="200" align="center">
        <template v-slot="scope">
          <el-button type="danger" @click="handleDelete(scope.row)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
export default {
  name: "File",
  data() {
    return {
      tableData: [],
      name: '',
      multiple: true,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      ids: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.request.get("/file/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 重置按钮
    resetQuery(){
      this.name = '';
      this.getList();
    },
    changeEnable(row) {
      this.request.post("/file/update", row).then(res => {
        if (res.code === '200') {
          this.$message.success("启用成功")
        }
      })
    },
    // 删除
    handleDelete(row){
      let _this = this;
      const fileIds = row.id || this.ids;
      this.$confirm('是否确认删除文件编号为"' + fileIds + '"的数据项?', '删除文件', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.request.delete("/file/"+fileIds).then(res=>{
          if(res.code === "200" || res.code === 200){
            _this.$message.success("删除成功")
          }else {
            _this.$message.error("删除失败")
          }
          this.getList();
        })
      }).catch(() => {
      });
    },
    handleFileUploadSuccess(res) {
      // console.log(res)
      this.getList()
    },
    download(url) {
      window.open(url)
    }
  }
}
</script>

<style scoped>

</style>

3.2 路由配置

{
    path: 'file',
    name: '文件管理',
    component: () => import('../views/File.vue'),
    meta: {
      title: '文件管理'
    }
},

3.3 Aside.vue

<el-menu-item index="/file">
  <i class="el-icon-files"></i>
  <span slot="title">文件管理</span>
</el-menu-item>

最终效果图

在这里插入图片描述

总结

  • 轻松实现文件上传和下载的前后端

写在最后

如果此文对您有所帮助,请帅戈靓女们务必不要吝啬你们的Zan,感谢!!不懂的可以在评论区评论,有空会及时回复。
文章会一直更新

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1699765.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【NumPy】关于numpy.clip()函数,看这一篇文章就够了

&#x1f9d1; 博主简介&#xff1a;阿里巴巴嵌入式技术专家&#xff0c;深耕嵌入式人工智能领域&#xff0c;具备多年的嵌入式硬件产品研发管理经验。 &#x1f4d2; 博客介绍&#xff1a;分享嵌入式开发领域的相关知识、经验、思考和感悟&#xff0c;欢迎关注。提供嵌入式方向…

H.机房【蓝桥杯】/数组链式前向星建图+堆优化版dijkstra

机房 数组链式前向星建图堆优化版dijkstra #include<iostream> #include<queue> #include<cstring> #include<vector> using namespace std; typedef pair<int,int> pii; //无向图开两倍 int e[200005],ne[200005],v[200005],h[200005],du[1000…

前端 JS 经典:Web 性能指标

什么是性能指标&#xff1a;Web Performance Metrics 翻译成 Web 性能指标&#xff0c;一般和时间有关系&#xff0c;在短时间内做更多有意义的事情。 一个站点表现得好与不好&#xff0c;标准在于用户体验&#xff0c;而用户体验好不好&#xff0c;有一套 RAIL 模型来衡量。这…

2024年上半年系统架构设计师真题-复原程度90%

前言 此次考试监考特别严格&#xff0c;草稿纸不允许带出考场&#xff0c;并且准考证上不允许任何写画&#xff0c;甚至连笔都允许带一支&#xff0c;所以下面的相关题目都是参考一些群友的提供&#xff0c;加上自己的记忆回顾&#xff0c;得到的结果。 其中综合知识部分的题…

修复谷歌 AdSense 的 Ads.Txt 无效的有收益损失风险提示

明月的 AdSense 账号后台一直都有“有收益损失风险 - 您需要纠正 ads.txt 文件存在的一些问题&#xff0c;以免严重影响您的收入。”的提示长达一年多了&#xff0c;这次重新开始投放谷歌 AdSense 广告后感觉需要解决掉这个问题了&#xff0c;因为已经全站使用了 CloudFlare&am…

《Ai学习笔记》-模型集成部署

后续大多数模型提升速度和精度&#xff1a; 提升速度&#xff1a; -知识蒸馏&#xff0c;以distillBert和tinyBert为代表 -神经网络优化技巧。prune来剪裁多余的网络节点&#xff0c;混合精度&#xff08;fp32和fp26混合来降低计算精度从从而实现速度的提升&#xff09; 提…

驾驭数字前沿--欧盟商会网络安全大会活动

本次安策参加由欧盟商会组织举办的--超越 2024 年网络安全大会&#xff1a;驾驭数字前沿大会(上海)&#xff0c;安策在大会上做了《2024数据威胁报告主题报告》并希望携手各行业伙伴&#xff0c;共同驾驭数字前沿的波涛&#xff0c;共创安全、合规、高效的数字未来。 【安策活动…

操作系统入门系列-MIT6.828(操作系统工程)学习笔记(二)----课程实验环境搭建(wsl2+ubuntu+quem+xv6)

MIT6.S081&#xff08;操作系统&#xff09;学习笔记 操作系统入门系列-MIT6.828&#xff08;操作系统&#xff09;学习笔记&#xff08;一&#xff09;---- 操作系统介绍与接口示例 操作系统入门系列-MIT6.828&#xff08;操作系统工程&#xff09;学习笔记&#xff08;二&am…

大模型的实践应用24-LLaMA-Factory微调通义千问qwen1.5-1.8B模型的实例

大家好,我是微学AI,今天给大家介绍一下大模型的实践应用24-LLaMA-Factory微调通义千问qwen1.5-1.8B模型的实例, LLaMA-Factory是一个专门用于大语言模型微调的框架,它支持多种微调方法,如LoRA、QLoRA等,并提供了丰富的数据集和预训练模型,便于用户进行模型微调。通义千问…

谷歌Google广告投放优势和注意事项!

谷歌Google作为全球最大的搜索引擎&#xff0c;谷歌不仅拥有庞大的用户基础&#xff0c;还提供了高度精准的广告投放平台&#xff0c;让广告主能够高效触达目标受众&#xff0c;实现品牌曝光、流量增长乃至销售转化的多重目标&#xff0c;云衔科技以专业服务助力您谷歌Google广…

C++笔记:红黑树与哈希表

1.容器rb_tree 按正常规则it遍历&#xff0c;便能得到排序状态不能使用rb_tree的iterators改变元素值两种插入操作&#xff1a;insert_unique()和insert_equal() template <class Key, class Value, class KeyOfValue, class Compare, class Allocalloc> class rb_tree…

基于Zookeeper的分布式锁

分布式锁的介绍 在Java的多线程部分&#xff0c;我们知道如果在单个jvm进程中&#xff0c;多个线程之间同时访问一个资源&#xff0c;此时会有多线程的安全问题。为了解决这个线程安全的问题&#xff0c;我们可以使⽤“锁”来实现。但是&#xff0c;多个jvm进程之间如果同时访问…

计算机毕业设计 | SpringBoot社区物业管理系统 小区管理(附源码)

1&#xff0c; 概述 1.1 课题背景 近几年来&#xff0c;随着物业相关的各种信息越来越多&#xff0c;比如报修维修、缴费、车位、访客等信息&#xff0c;对物业管理方面的需求越来越高&#xff0c;我们在工作中越来越多方面需要利用网页端管理系统来进行管理&#xff0c;我们…

【源码】java + uniapp交易所源代码/带搭建教程java交易所/完整源代码

java uniapp交易所源代码/带搭建教程java交易所/完整源代码 带简洁教程&#xff0c;未测 java uniapp交易所源代码/带搭建教程java交易所/完整源代码 - 吾爱资源网

软件需求开发管理规程-Word原件(配套软件全资料文档)

1. 目的 2. 适用范围 3. 参考文件 4. 术语和缩写 5. 需求获取的方式 5.1. 与用户交谈向用户提问题 5.1.1. 访谈重点注意事项 5.1.2. 访谈指南 5.2. 参观用户的工作流程 5.3. 向用户群体发调查问卷 5.4. 已有软件系统调研 5.5. 资料收集 5.6. 原型系统调研 5.6.1. …

Android11热点启动和关闭

Android官方关于Wi-Fi Hotspot (Soft AP) 的文章&#xff1a;https://source.android.com/docs/core/connect/wifi-softap?hlzh-cn 在 Android 11 的WifiManager类中有一套系统 API 可以控制热点的开和关&#xff0c;代码如下&#xff1a; 开启热点&#xff1a; // SoftApC…

Java进阶学习笔记27——StringBuilder、StringBuffer

StringBuilder&#xff1a; StringBuilder代表可变字符串对象&#xff0c;相当于一个容器&#xff0c;它里面装的字符串是可以改变的&#xff0c;就是用来操作字符串的。 好处&#xff1a; StringBuilder比String更适合做字符串的修改操作&#xff0c;效率会更高&#xff0c;…

基于Ruoyi-Cloud-Plus重构黑马项目-学成在线

文章目录 一、系统介绍二、系统架构图三、参考教程四、演示图例机构端运营端用户端开发端 一、系统介绍 毕设&#xff1a;基于主流微服务技术栈的在线教育系统的设计与实现 前端仓库&#xff1a;https://github.com/Xiamu-ssr/Dragon-Edu-Vue3 后端仓库&#xff1a;https://g…

Nodejs(文件操作,构建服务器,express,npm)

文章目录 文件操作1.读取文件1&#xff09;步骤2&#xff09;范例 2.写文件1&#xff09;步骤2&#xff09;范例 3.删除文件4.重命名文件夹5删除文件夹 Url1.url.parse()2.url.fomat() Query1.query.parse()2.query.stringfy()3.编码和解码 第三方模块1.nodemailer2.body-parse…

学 C/C++ 具体能干什么?

学习 C 和 C 后&#xff0c;你可以从事许多不同的工作和项目&#xff0c;这两种语言以其高性能和低级控制而闻名&#xff0c;特别适合以下几个领域&#xff1a; 1. 系统编程 C 和 C 是系统编程的首选语言&#xff0c;适用于操作系统、驱动程序和嵌入式系统开发。 操作系统开发…