SpringBoot整合Hutool實(shí)現(xiàn)文件上傳的使用示例
前言
我相信我們?cè)谌粘i_發(fā)中,難免會(huì)遇到對(duì)各種媒體文件的操作,由于業(yè)務(wù)需求的不同對(duì)文件操作的代碼實(shí)現(xiàn)也大不相同
數(shù)據(jù)庫(kù)設(shè)計(jì)
/* 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 '文件大?。╧b)', `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 '上傳時(shí)間', 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:/項(xiàng)目/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("開啟狀態(tài)") private String download; @ApiModelProperty("是否刪除") private Boolean isDelete; @ApiModelProperty("文件md5") private String md5; @ApiModelProperty("開啟狀態(tài)") private Boolean enable; @ApiModelProperty("上傳時(shí)間") 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("分頁(yè)查詢所有文件信息") @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("當(dāng)前用戶------{}", currentUser); return Result.success(fileService.page(page, queryWrapper)); } @ApiOperation("根據(jù)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("根據(jù)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("-", "/"); // 定義一個(gè)文件唯一的標(biāo)識(shí)碼 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; // 判斷目錄是否存在。不存在就創(chuàng)建 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); // 查詢數(shù)據(jù)庫(kù)有沒有當(dāng)前md5 Files one = getFileMd5(md5); String url; if (one != null) { uploadFile.delete(); return Result.waring("文件重復(fù)", one.getUrl()); } else { url = request.getScheme() + "://" + ip + ":" + port + path + fileUUID; } // 存入數(shù)據(jù)庫(kù) 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); } }
配置靜態(tài)資源映射
@Value("${files.upload.path}") private String filePath; @Value("${files.upload.location}") private String fileLocation; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //注冊(cè)配置類,使用addResourceHandlers方法,將本地路徑fileLocation映射到filePath路由上。 registry.addResourceHandler(filePath).addResourceLocations(fileLocation); WebMvcConfigurer.super.addResourceHandlers(registry); }
到此這篇關(guān)于SpringBoot整合Hutool實(shí)現(xiàn)文件上傳的使用示例的文章就介紹到這了,更多相關(guān)SpringBoot Hutool文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?boot集成easy?excel實(shí)現(xiàn)導(dǎo)入導(dǎo)出功能
這篇文章主要介紹了Spring?boot集成easy?excel實(shí)現(xiàn)導(dǎo)入導(dǎo)出操作,使用easyexcel,首先要引入easyexcel的maven依賴,具體的版本根據(jù)你的需求去設(shè)置,本文結(jié)合實(shí)例代碼講解的非常詳細(xì),需要的朋友可以參考下2024-05-05SpringBoot?AOP中JoinPoint的使用方式和通知切點(diǎn)表達(dá)式
這篇文章主要介紹了SpringBoot?AOP中JoinPoint的使用方式和通知切點(diǎn)表達(dá)式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05淺談Java變量賦值運(yùn)算符及相關(guān)實(shí)例
這篇文章主要介紹了Java賦值運(yùn)算符的一些知識(shí),需要的朋友可以參考下。2017-09-09SpringData JPA Mongodb查詢部分字段問題
這篇文章主要介紹了SpringData JPA Mongodb查詢部分字段問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08Java Socket編程實(shí)例(二)- UDP基本使用
這篇文章主要講解Java Socket編程中UDP的基本使用,希望能給大家做一個(gè)參考。2016-06-06Java弱鍵集合WeakHashMap及ConcurrentCache原理詳解
這篇文章主要介紹了Java弱鍵集合WeakHashMap及ConcurrentCache原理詳解,基于哈希表的Map接口實(shí)現(xiàn),支持null鍵和值,但是WeakHashMap具有弱鍵,可用來實(shí)現(xiàn)緩存存儲(chǔ),在進(jìn)行GC的時(shí)候會(huì)自動(dòng)回收鍵值對(duì),需要的朋友可以參考下2023-09-09