使用Springboot+Vue实现文件上传和下载功能

 更新时间:2024年09月24日 09:26:34   作者:等雨停、  
本文介绍了如何使用Springboot结合Vue进行图书信息管理系统开发,包括数据库表的创建,实体类、Dao层、Service层和Controller层的编写,重点讲解了文件上传和下载功能的实现,感兴趣的朋友跟随小编一起看看吧

图书信息管理的增删改查

创建数据库表

CREATE TABLE `book` (
    `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '图书名称',
`price` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '图书价格',
`author` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '图书作者',
`press` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '图书出版社',
`img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '图书封面',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

创建实体类Book.java

@Table(name = "book")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "name")
    private String name;
    @Column(name = "price")
    private String price;
    @Column(name = "author")
    private String author;
    @Column(name = "press")
    private String press;
    @Column(name = "img")
    private String img;
}

BookDao.java BookMapper.xml

import com.example.entity.Book;
import com.example.entity.Params;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
@Repository
public interface BookDao extends Mapper<Book> {
    List<Book> findBySearch(@Param("params") Params params);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.BookDao">
<select id="findBySearch" resultType="com.example.entity.Book">
select * from book
<where>
<if test="params != null and params.name != null and params.name != ''">
and name like concat('%', #{ params.name }, '%')
</if>
<if test="params != null and params.author != null and params.author != ''">
and author like concat('%', #{ params.author }, '%')
</if>
</where>
</select>
</mapper>

BookService.java

import com.example.dao.BookDao;
import com.example.entity.Book;
import com.example.entity.Params;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class BookService {
    @Resource
    private BookDao bookDao;
    public PageInfo<Book> findBySearch(Params params) {
        // 开启分页查询
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        // 接下来的查询会自动按照当前开启的分页设置来查询
        List<Book> list = bookDao.findBySearch(params);
        return PageInfo.of(list);
    }
    public void add(Book book) {
        bookDao.insertSelective(book);
    }
    public void update(Book book) {
        bookDao.updateByPrimaryKeySelective(book);
    }
    public void delete(Integer id) {
        bookDao.deleteByPrimaryKey(id);
    }
}

BookController.java

import com.example.common.Result;
import com.example.entity.Book;
import com.example.entity.Params;
import com.example.service.BookService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@CrossOrigin
@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    private BookService bookService;
    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Book> info = bookService.findBySearch(params);
        return Result.success(info);
    }
    @PostMapping
    public Result save(@RequestBody Book book) {
        if (book.getId() == null) {
            bookService.add(book);
        } else {
            bookService.update(book);
        }
        return Result.success();
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        bookService.delete(id);
        return Result.success();
    }
}

图书封面文件上传

FileController.java

package com.example.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
/**
 *  文件上传接口
 */
@RestController
@RequestMapping("/files")
public class FileController {
    // 文件上传存储路径
    private static final String filePath = System.getProperty("user.dir") + "/file/";
    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        synchronized (FileController.class) {
            String flag = System.currentTimeMillis() + "";
            String fileName = file.getOriginalFilename();
            try {
                if (!FileUtil.isDirectory(filePath)) {
                    FileUtil.mkdir(filePath);
                }
                // 文件存储形式:时间戳-文件名
                FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
                System.out.println(fileName + "--上传成功");
                Thread.sleep(1L);
            } catch (Exception e) {
                System.err.println(fileName + "--文件上传失败");
            }
            return Result.success(flag);
        }
    }
    /**
     * 获取文件
     */
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }
}

上传下载接口不能拦截,需要放行

// 加自定义拦截器JwtInterceptor,设置拦截规则
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor).addPathPatterns("/api/**")
.excludePathPatterns("/api/files/**")
.excludePathPatterns("/api/admin/login")
.excludePathPatterns("/api/admin/register");
}

BookView.vue

el-upload:Element - The world's most popular Vue UI framework

<el-form-item label="图书封面" label-width="20%">
<el-upload action="http://localhost:8080/api/files/upload" :on-success="successUpload">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-form-item>
successUpload(res) {
    this.form.img = res.data;
},

图书封面预览、下载

el-image:Element - The world's most popular Vue UI framework

<el-table-column label="图书封面">
<template v-slot="scope">
<el-image
style="width: 70px; height: 70px; border-radius: 50%"
:src="'http://localhost:8080/api/files/' + scope.row.img"
:preview-src-list="['http://localhost:8080/api/files/' + scope.row.img]">
</el-image>
</template>
</el-table-column>
<el-button type="primary" @click="down(scope.row.img)">下载</el-button>
down(flag) {
    location.href = 'http://localhost:8080/api/files/' + flag
}

到此这篇关于使用Springboot+Vue实现文件上传和下载的文章就介绍到这了,更多相关Springboot Vue文件上传和下载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 通过源代码分析Mybatis的功能流程详解

    通过源代码分析Mybatis的功能流程详解

    这篇文章主要介绍了通过源代码分析Mybatis的功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • Java 堆内存溢出原因分析

    Java 堆内存溢出原因分析

    这篇文章主要介绍了Java 堆内存溢出原因分析,任何使用过基于 Java 的企业级后端应用的软件开发者都会遇到过这种报错,java.lang.OutOfMemoryError:Java heap space。,需要的朋友可以参考下
    2019-06-06
  • Java线程之线程同步synchronized和volatile详解

    Java线程之线程同步synchronized和volatile详解

    这篇文章主要介绍了Java线程之线程同步synchronized和volatile详解,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • 基于spring+quartz的分布式定时任务框架实现

    基于spring+quartz的分布式定时任务框架实现

    在Spring中的定时任务功能,最好的办法当然是使用Quartz来实现。这篇文章主要介绍了基于spring+quartz的分布式定时任务框架实现,有兴趣的可以了解一下。
    2017-01-01
  • 编写Java代码对HDFS进行增删改查操作代码实例

    编写Java代码对HDFS进行增删改查操作代码实例

    这篇文章主要介绍了Java代码对HDFS进行增删改查操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • SpringBoot 中的异步处理机制详解

    SpringBoot 中的异步处理机制详解

    本文介绍了异步处理的基础配置、线程池的自定义以及常见应用场景,在实际应用中,异步处理可以有效提升应用的性能,改善用户体验,但同时也需要我们合理管理线程池,确保系统资源的高效利用,感兴趣的朋友跟随小编一起看看吧
    2025-01-01
  • 如何基于java实现Gauss消元法过程解析

    如何基于java实现Gauss消元法过程解析

    这篇文章主要介绍了如何基于java实现Gauss消元法过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • Java基于IDEA实现http编程的示例代码

    Java基于IDEA实现http编程的示例代码

    这篇文章主要介绍了Java基于IDEA实现http编程的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • 如何使用spring ResponseEntity处理http响应

    如何使用spring ResponseEntity处理http响应

    这篇文章主要介绍了如何使用spring ResponseEntity处理http响应的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Spring如何替换掉默认common-logging.jar

    Spring如何替换掉默认common-logging.jar

    这篇文章主要介绍了Spring如何替换掉默认common-logging.jar,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05

最新评论