SpringBoot整合Hutool实现文件上传下载

这篇具有很好参考价值的文章主要介绍了SpringBoot整合Hutool实现文件上传下载。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

我相信我们在日常开发中,难免会遇到对各种媒体文件的操作,由于业务需求的不同对文件操作的代码实现也大不相同

数据库设计

/*
 Navicat Premium Data Transfer

 Source Server         : MySQL 5.5
 Source Server Type    : MySQL
 Source Server Version : 50554 (5.5.54)
 Source Host           : localhost:3306
 Source Schema         : tgadmin

 Target Server Type    : MySQL
 Target Server Version : 50554 (5.5.54)
 File Encoding         : 65001

 Date: 20/06/2023 03:07:47
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for sys_file
-- ----------------------------
DROP TABLE IF EXISTS `sys_file`;
CREATE TABLE `sys_file`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '文件id',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件名',
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件类型',
  `size` bigint(20) NULL DEFAULT NULL COMMENT '文件大小(kb)',
  `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '访问路径',
  `location` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件地址',
  `download` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '下载地址',
  `md5` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件md5',
  `is_Delete` tinyint(1) NULL DEFAULT 0 COMMENT '是否删除 0:未删除 1:删除',
  `enable` tinyint(1) NULL DEFAULT 1 COMMENT '是否禁用链接  1:可用  0:禁用用',
  `upload_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `uni_md5`(`md5`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 64 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '文件表' ROW_FORMAT = Compact;

SET FOREIGN_KEY_CHECKS = 1;

yaml配置我们的上传路径

# 文件上传配置
files:
  ip: localhost
  upload:
    location: file:F:/项目/SpringBoot+vue/tg-admin/server/files/
    path: /img/**

上传

maven配置

<!--        hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.15</version>
        </dependency>
<!--        MybatisPlus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

文件类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.sql.Timestamp;

/**
 * @Program: admin
 * @ClassName File
 * @Author: liutao
 * @Description: 文件
 * @Create: 2023-03-16 18:51
 * @Version 1.0
 **/

@Data
@TableName("sys_file")
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("文件表")
public class Files implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty("文件id")
    @TableId(type = IdType.AUTO)
    private Integer id;

    @ApiModelProperty("文件名称")
    private String name;

    @ApiModelProperty("文件类型")
    private String type;

    @ApiModelProperty("文件大小")
    private Long size;

    @ApiModelProperty("文件地址")
    private String location;

    @ApiModelProperty("访问url")
    private String url;

    @ApiModelProperty("开启状态")
    private String download;

    @ApiModelProperty("是否删除")
    private Boolean isDelete;

    @ApiModelProperty("文件md5")
    private String md5;

    @ApiModelProperty("开启状态")
    private Boolean enable;

    @ApiModelProperty("上传时间")
    private Timestamp uploadTime;
}

文件接口 

import cn.hutool.core.date.DateUtil;
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.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.admin.common.Result;
import com.tg.admin.entity.Files;
import com.tg.admin.entity.User;
import com.tg.admin.service.FileService;
import com.tg.admin.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @Program: admin
 * @ClassName: FileController
 * @Author: liutao
 * @Description: 文件处理
 * @Create: 2023-03-16 18:15
 * @Version 1.0
 **/
@Api(tags = "文件接口")
@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Value("${files.ip}")
    private String ip;
    @Value("${server.port}")
    private String port;
    @Value("${files.upload.path}")
    private String path;
    @Value("${files.upload.location}")
    private String fileUploadPath;

    @Autowired
    private FileService fileService;

    @ApiOperation("分页查询所有文件信息")
    @GetMapping("/page")
    public Result<Files> findPage(@RequestParam Integer pageNum,
                                  @RequestParam Integer pageSize,
                                  @RequestParam String name,
                                  @RequestParam String type) {
        IPage<Files> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_Delete", false);
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (!"".equals(type)) {
            queryWrapper.like("type", type);
        }
        User currentUser = JwtUtil.getCurrentUser();
        log.info("当前用户------{}", currentUser);
        return Result.success(fileService.page(page, queryWrapper));
    }


    @ApiOperation("根据id删除文件")
    @DeleteMapping("/{id}")
    public Result<Files> delete(@PathVariable Integer id) {
        Files files = fileService.getById(id);
        files.setIsDelete(true);
        fileService.updateById(files);
        return Result.success();
    }


    @ApiOperation("根据id批量删除文件")
    @PostMapping("del/batch")
    public Result<Files> deleteBatch(@RequestBody List<Integer> ids) {
        QueryWrapper<Files> queryWrapper = new QueryWrapper<Files>();
        queryWrapper.in("id", ids);
        List<Files> files = fileService.list(queryWrapper);
        files.forEach(file -> {
            file.setIsDelete(true);
            fileService.updateById(file);
        });
        return Result.success();
    }

    @ApiOperation(value = "更新或新增", httpMethod = "POST")
    @PostMapping("/update")
    public Result<Files> save(@RequestBody Files files) {
        return Result.success(fileService.saveOrUpdate(files));
    }


    /**
     * @MethodName: upload
     * @description: 文件上传
     * @Author: LiuTao
     * @Param: [file]
     * @UpdateTime: 2023/3/16 18:39
     * @Return: java.lang.String
     * @Throw: IOException
     **/
    @ApiOperation("上传文件接口")
    @PostMapping("/upload")
    public Result<Files> upload(@RequestParam MultipartFile file,
                                HttpServletRequest request) throws IOException {
        // 文件原始名
        String originalFilename = file.getOriginalFilename();
        // 文件类型
        String type = FileUtil.extName(originalFilename);
        // 文件大小
        long size = file.getSize();
        String today = DateUtil.today().replace("-", "/");
        // 定义一个文件唯一的标识码
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + type;
        // 下载地址
        String download = request.getScheme() + "://" + ip + ":" + port + "/file/" + fileUUID;
        // 重命名文件
        fileUploadPath = fileUploadPath.replace("file:", "");
        path = path.replace("**", "") + today + StrUtil.C_SLASH;
        // 判断目录是否存在。不存在就创建
        if (!FileUtil.exist(fileUploadPath + today)) {
            FileUtil.mkdir(fileUploadPath + today);
        }
        // 上传的文件
        File uploadFile = new File(fileUploadPath + today + StrUtil.C_SLASH + fileUUID);
        System.out.println(fileUploadPath);
        // 文件存入磁盘
        file.transferTo(uploadFile);
        // 获取文件md5
        String md5 = SecureUtil.md5(uploadFile);
        // 查询数据库有没有当前md5
        Files one = getFileMd5(md5);
        String url;
        if (one != null) {
            uploadFile.delete();
            return Result.waring("文件重复", one.getUrl());
        } else {
            url = request.getScheme() + "://" + ip + ":" + port + path + fileUUID;
        }
        // 存入数据库
        Files saveFile = new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size / 1024);
        saveFile.setLocation(uploadFile.getCanonicalPath());
        saveFile.setUrl(url);
        saveFile.setDownload(download);
        saveFile.setMd5(md5);
        fileService.save(saveFile);
        return Result.success(url);
    }

    @ApiOperation("下载文件接口")
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID,
                         HttpServletResponse response) throws IOException {
        Files one = fileService
                .lambdaQuery()
                .like(Files::getLocation, fileUUID)
                .one();
        File uploadFile = new File(one.getLocation());
        ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename =" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");
        byte[] bytes = FileUtil.readBytes(uploadFile);
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }

    private Files getFileMd5(String md5) {
        QueryWrapper<Files> wrapper = new QueryWrapper<>();
        wrapper.eq("md5", md5);
        List<Files> list = fileService.list(wrapper);
        return list.size() == 0 ? null : list.get(0);
    }
}

配置静态资源映射文章来源地址https://www.toymoban.com/news/detail-783268.html

    @Value("${files.upload.path}")
    private String filePath;
    @Value("${files.upload.location}")
    private String fileLocation;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //注册配置类,使用addResourceHandlers方法,将本地路径fileLocation映射到filePath路由上。
        registry.addResourceHandler(filePath).addResourceLocations(fileLocation);
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

到了这里,关于SpringBoot整合Hutool实现文件上传下载的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用hutool进行ftp文件下载和上传

    2024年02月11日
    浏览(32)
  • 调用hutool包调用http接口处理文件流-文件的上传下载工具类

    hutool工具类get请求获取流: InputStream inputStream = HttpRequest.get(fileUrl).execute().bodyStream(); hutool工具类post请求上传文件流: String resp = HttpRequest.post(url).header(Header.CONTENT_TYPE.getValue(), ContentType.MULTIPART.getValue()).form(params).execute().body(); 完成代码

    2024年01月17日
    浏览(41)
  • SpringBoot 如何实现文件上传和下载

    当今Web应用程序通常需要支持文件上传和下载功能,Spring Boot提供了简单且易于使用的方式来实现这些功能。在本篇文章中,我们将介绍Spring Boot如何实现文件上传和下载,同时提供相应的代码示例。 Spring Boot提供了Multipart文件上传的支持。Multipart是HTTP协议中的一种方式,用

    2024年02月15日
    浏览(25)
  • SpringBoot+MinIO 实现文件上传、读取、下载、删除

    一、 MinIO 二、 MinIO安装和启动 三、 pom.xml 四、 applicatin.properties(配置文件) 五、 编写Java业务类

    2024年02月09日
    浏览(26)
  • springboot+微信小程序实现文件上传下载(预览)pdf文件

    实现思路: 选择文件 wx.chooseMessageFile ,官方文档: https://developers.weixin.qq.com/miniprogram/d e v/api/media/image/wx.chooseMessageFile.html 上传文件 `wx,uploadFile` , 官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html 查看所有上传的pdf文件,显示在页面上 点击pdf文件

    2024年02月08日
    浏览(39)
  • Springboot + MySQL + html 实现文件的上传、存储、下载、删除

    实现步骤及效果呈现如下: 1.创建数据库表: 表名:file_test 存储后的数据: 2.创建数据库表对应映射的实体类: import com.baomidou.mybatisplus.annotation.IdType ; import com.baomidou.mybatisplus.annotation. TableField ; import com.baomidou.mybatisplus.annotation. TableId ; import com.baomidou.mybatisplus.annotation. Tab

    2024年04月29日
    浏览(27)
  • SpringBoot实现文件上传和下载笔记分享(提供Gitee源码)

    前言:这边汇总了一下目前SpringBoot项目当中常见文件上传和下载的功能,一共三种常见的下载方式和一种上传方式,特此做一个笔记分享。 目录 一、pom依赖 二、yml配置文件 三、文件下载

    2024年02月11日
    浏览(28)
  • 一张图带你学会入门级别的SpringBoot实现文件上传、下载功能

    🧑‍💻作者名称:DaenCode 🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。 😎人生感悟:尝尽人生百味,方知世间冷暖。 📖所属专栏:SpringBoot实战 标题 一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码) 一张思维导图带你学会Springboot创

    2024年02月12日
    浏览(59)
  • 基于SpringBoot实现文件上传和下载(详细讲解And附完整代码)

    目录 一、基于SpringBoot实现文件上传和下载基于理论 二、详细操作步骤 文件上传步骤: 文件下载步骤: 三、前后端交互原理解释  四、小结  博主介绍:✌专注于前后端领域开发的优质创作者、秉着互联网精神开源贡献精神,答疑解惑、坚持优质作品共享。本人是掘金/腾讯

    2024年04月11日
    浏览(40)
  • 【java】java实现大文件的分片上传与下载(springboot+vue3)

    源码: https://gitee.com/gaode-8/big-file-upload 演示视频 https://www.bilibili.com/video/BV1CA411f7np/?vd_source=1fe29350b37642fa583f709b9ae44b35 对于超大文件上传我们可能遇到以下问题 • 大文件直接上传,占用过多内存,可能导致内存溢出甚至系统崩溃 • 受网络环境影响,可能导致传输中断,只能重

    2024年02月02日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包