首页 > 其他分享 >springboot+vue整合文件,照片上传

springboot+vue整合文件,照片上传

时间:2023-01-23 17:22:19浏览次数:62  
标签:文件 vue springboot String file import fileUUID 上传 md5

1.建立一个File的数据库

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 '1' COMMENT '是否禁用链接',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Files.sql

这里采用的都是假删除,is_delete如果是true的话就是删除,否则不是删除

 2.Files.java和Filesmapper和FileController的建立

这里也可以用代码生成器来生成

 Files.java

Filesmapper.java

FilesMapper.xml

 

 

 Filescontroller

3.Filescontroller中的文件上传,下载和删除

 

 

在本地磁盘中要储存的地址,我们采用现在application.yml中定义:然后引入的时候就是这样

//将resources中的application.yml中的路径引入
@Value("${files.upload.path}")
private String fileUploadPath;

 

 

 

 

 这里为什么要用md5呢,就是如果每个文件只是改了一个名字然后在传到本地磁盘中去的话,这个会浪费内存,然后我们就设置了一个md5来标识文件

package com.xxxx.demo.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.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxxx.demo.common.Result;
import com.xxxx.demo.entity.Files;
import com.xxxx.demo.mapper.FileMapper;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName FileController
 * @Description 文件上传
 * @Author Lishipu
 * @Date 2023/1/20 20:23
 * Version 1.0
 **/
@RestController
@RequestMapping("/file")
public class FileController {
    //将resources中的application.yml中的路径引入
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Resource
    private FileMapper fileMapper;
    /*
     * @Author lishipu
     * @Description 文件上传接口
     * @Date 20:24 2023/1/20
     * @Param  前端传递过来的文件
     * @return
     **/
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//获得名字
        String type = FileUtil.extName(originalFilename);//获得类型,像.png
        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,通过对文件的md5,避免上传相同内容的文件
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFileByMd5(md5);
        if (dbFiles != null) { // 文件已存在
            url = dbFiles.getUrl();
            //由于文件已经存在,所以删除刚才上传的重复的文件
            uploadFile.delete();
        } else {
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件,则不删除刚才上传的文件
            url = "http://localhost:9090/file/" + fileUUID;
        }
        //储存到数据库中
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);//插入

        return url;
    }
    /*
     * @Author lishipu
     * 文件下载接口   http://localhost:9090/file/{fileUUID}
     * @Description 文件的下载
     * @Date 21:16 2023/1/20
     * @Param
     * @return
     **/
    //fileUUID是uuid加点加类型
    @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();
    }

    /**
     * @Author lishipu
     * @Description 通用文件的md5查询文件‘
     * @Date 21:43 2023/1/20
     * @Param [md5]
     * @return com.xxxx.demo.entity.Files
     **/
    private Files getFileByMd5(String md5) {
        // 查询文件的md5是否存在
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> filesList = fileMapper.selectList(queryWrapper);
        return filesList.size() == 0 ? null : filesList.get(0);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Files files) {
        return Result.success(fileMapper.updateById(files));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(true);
        fileMapper.updateById(files);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        // select * from sys_file where id in (id,id,id...)
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<Files> files = fileMapper.selectList(queryWrapper);
        for (Files file : files) {//这里也是采用的假删除
            file.setIsDelete(true);
            fileMapper.updateById(file);
        }
        return Result.success();
    }

    /*
     * @Author lishipu
     * @Description 分页查询接口
     * @Date 22:34 2023/1/20
     * @Param
     * @return
     **/
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        // 查询未删除的记录,这里采用的假删除
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        return Result.success(fileMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper));
    }
}

这里主要说一下文件的上传和下载

文件的上传,这里可以也应该可以不用传到磁盘中去

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//获得名字
        String type = FileUtil.extName(originalFilename);//获得类型,像.png
        long size = file.getSize();//获得大小
        //定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID=uuid+StrUtil.DOT+type;//要加上.png或者.word

        File uploadFile = new File(fileUploadPath + fileUUID);
        //先存储到磁盘中去
        File ParentFile =uploadFile.getParentFile();
        //判断配置的文件目录是否存在,若不存在则创建一个新的文件目录
        if(!ParentFile.exists()){
            ParentFile.mkdirs();
        }
        String url;
        //获取文件的Md5,通过对文件的md5,避免上传相同内容的文件
        String md5 = SecureUtil.md5(file.getInputStream());
        // 从数据库查询是否存在相同的记录
        Files dbFiles = getFileByMd5(md5);
        if (dbFiles != null) { // 文件已存在
            url = dbFiles.getUrl();
            //由于文件已经存在,所以删除刚才上传的重复的文件
            uploadFile.delete();
        } else {
            // 上传文件到磁盘
            file.transferTo(uploadFile);
            // 数据库若不存在重复文件,则不删除刚才上传的文件
            url = "http://localhost:9090/file/" + fileUUID;
        }
        //储存到数据库中
        Files saveFile = new Files();//定义实体类
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileMapper.insert(saveFile);//插入
        return url;
    }

文件的下载:这里文件前端文件的接口是http://localhost:9090/file/{fileUUID}

 /*
     * @Author lishipu
     * 文件下载接口   http://localhost:9090/file/{fileUUID}
     * @Description 文件的下载
     * @Date 21:16 2023/1/20
     * @Param
     * @return
     **/
    //fileUUID是uuid加点加类型
    @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();
    }

4.整合前端:

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="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-upload action="http://localhost:9090/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-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗?"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>

    </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 slot-scope="scope">
          <el-button type="primary" @click="download(scope.row.url)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="启用">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" 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 slot-scope="scope">
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗?"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </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: '',
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      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
      })
    },
    changeEnable(row) {
      this.request.post("/file/update", row).then(res => {
        if (res.code === '200') {
          this.$message.success("操作成功")
        }
      })
    },
    del(id) {
      this.request.delete("/file/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {//多选
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      this.request.post("/file/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("批量删除失败")
        }
      })
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    handleFileUploadSuccess(res) {
      console.log(res)
      this.load()
    },
    download(url) {
      window.open(url)
    }
  }
}
</script>

<style scoped>

</style>
File.vue

 

添加路由

 

 

然后最后的样子就是这样的

 看下载这个地方:

 

 

 

 看看这个多选,删除的地方:

 

 

 

 

 看看后端:

 

 

下面是更新头像

 

标签:文件,vue,springboot,String,file,import,fileUUID,上传,md5
From: https://www.cnblogs.com/lipu123/p/17065257.html

相关文章

  • SpringBoot单元测试
    接上一篇:https://www.cnblogs.com/uncleyong/p/17065293.html添加依赖<dependency><groupId>org.springframework.boot</groupId><a......
  • SpringBoot整合MyBatis
     添加pom依赖<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.18<......
  • SpringBoot集成JWT实现token验证
    一、简介Jwt全称是:jsonwebtoken。它将用户信息加密到token里,服务器不保存任何用户信息。服务器通过使用保存的密钥验证token的正确性,只要正确即通过验证。优点简洁......
  • 【Azure 存储服务】.NET7.0 示例代码之上传大文件到Azure Storage Blob (一)
    问题描述在使用Azure的存储服务时候,如果上传的文件大于了100MB,1GB的情况下,如何上传呢? 问题解答使用Azure存储服务时,如果要上传文件到AzureBlob,有很多种工具可以实现。如:A......
  • Vue3中的异步组件defineAsyncComponentAPI的用法示例
    介绍当我们的项目达到一定的规模时,对于某些组件来说,我们并不希望一开始全部加载,而是需要的时候进行加载;这样的做得目的可以很好的提高用户体验。为了实现这个功能,Vue3中为我......
  • Vuw2和Vue3如何使用ref获取元素节点?
    Vue2中<template><divid="app"><divref="echohye">新年快乐</div></div></template><script>exportdefault{mounted(){console.log(this.$refs.echohye)......
  • 【SpringBoot】源码之 Java16新特性:【instanceOf】
    在java16之前,我们要进行instanceOf判断一般会伴随着强转操作,就像这样:if(objinstanceofString){Strings=(String)obj;...}这样的书写方式看起来比......
  • node+express+ multer 实现文件上传入门
    文件上传文件上传需要借助一个中间件multer因此我们需要安装cnpminstallmulter--save前端界面在express创建的项目下的public/upload目录下创建indexfileupload.htm......
  • vue关于通过下标更改数组的理解
    案例1:通过下标更改数组失败<template><div><el-button@click="handlerMe2">改变arr</el-button><div>{{arr}}--arr</div></div></template><script>ex......
  • Vue 快速入门(四)
    前面已经介绍Vue常用指令的基本应用,这篇介绍Vue的一些特殊属性的使用。01-计算属性Computed计算属性关键词:Computed。计算属性在处理一些复杂逻辑时是很有用的。......