package com.de.debook.utils; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class FileUploadUtils { /** * @param * @description: 生成一个唯一的ID * @return: java.lang.String */ public static String createUUID() { String s = UUID.randomUUID().toString(); String s2 = s.substring(24).replace("-", ""); return s2.toUpperCase(); } /** * @description: 得到一个保证不重复的临时文件名 * @return: java.lang.String */ public static String createTmpFileName(String suffix) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); String datestr = sdf.format(new Date()); String name = datestr + "-" + createUUID() + "." + suffix; return name; } /** * @param fileName 原始文件名 * @description: 得到文件的后缀名 * @return: java.lang.String */ public static String fileSuffix(String fileName) { int p = fileName.lastIndexOf('.'); if (p >= 0) { return fileName.substring(p + 1).toLowerCase(); } return ""; } public static void deleteDir(String dirPath) { File file = new File(dirPath); if (file.isFile()) { file.delete(); } else { File[] files = file.listFiles(); if (files == null) { file.delete(); } else { for (int i = 0; i < files.length; i++) { deleteDir(files[i].getAbsolutePath()); } file.delete(); } } } public static byte[] getFileByteArray(File file) { long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { System.out.println("file too big..."); return null; } byte[] buffer = null; try (FileInputStream fi = new FileInputStream(file)) { buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } // 确保所有数据均被读取 if (offset != buffer.length) { throw new IOException("Could not completely read file" + file.getName()); } } catch (Exception e) { e.printStackTrace(); } return buffer; } public static void writeBytesToFile(byte[] bs, String file) throws IOException { OutputStream out = new FileOutputStream(file); InputStream is = new ByteArrayInputStream(bs); byte[] buff = new byte[1024]; int len = 0; while ((len = is.read(buff)) != -1) { out.write(buff, 0, len); } is.close(); out.close(); } }

时间: 2023-12-25 13:06:25 浏览: 36
这是一个文件上传工具类,包含以下方法: 1. createUUID():用于生成唯一的UUID。 2. createTmpFileName(String suffix):用于生成一个不重复的临时文件名,包括时间戳和UUID。 3. fileSuffix(String fileName):用于获取文件的后缀名。 4. deleteDir(String dirPath):用于删除指定目录下的所有文件和子目录。 5. getFileByteArray(File file):用于将文件转换成byte数组。 6. writeBytesToFile(byte[] bs, String file):用于将byte数组写入指定的文件中。 这些方法可以帮助我们实现文件上传功能。需要注意的是,该工具类中的一些方法可能会抛出IOException异常,需要在调用时进行处理。
相关问题

package com.de.debook.init; import com.de.debook.constant.WebConstant; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import org.springframework.util.ClassUtils; @Component public class InitConfig implements CommandLineRunner { @Override public void run(String... strings) throws Exception { // 项目路径 WebConstant.WEB_FILE_ROOT = ClassUtils.getDefaultClassLoader() .getResource("").getPath().substring(1); // 图片存储目录 WebConstant.FILE_STORAGE_ROOT = WebConstant.WEB_FILE_ROOT + "static/images/"; } }

这是一个Spring Boot项目的初始化配置类,实现了CommandLineRunner接口,用于在Spring Boot应用程序启动时执行一些初始化操作。 具体来说,该配置类的run方法实现了以下两个操作: 1. 获取项目路径:通过ClassUtils.getDefaultClassLoader().getResource("").getPath()方法获取当前类所在的classpath路径,然后通过substring(1)方法去掉开头的“/”字符,得到项目的根路径。 2. 设置图片存储目录:将WebConstant.WEB_FILE_ROOT和"static/images/"拼接起来,得到图片存储目录的绝对路径,保存到WebConstant.FILE_STORAGE_ROOT中。 这里的WebConstant是一个常量类,用于保存项目中的常量值。通过这个配置类,我们可以方便地获取项目路径和设置图片存储目录,从而方便地进行文件操作。

package com.de.debook.controller; import com.de.debook.bo.ResponseBean; import com.de.debook.constant.WebConstant; import com.de.debook.utils.FileUploadUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.Map; @RestController public class UploadFileController { private static final int FILE_SIZE_MAX = 20 * 1024 * 1024; // 上传限制大小 /** * @param multipartFile * @description: 通用文件上传处理器 * @return: java.util.Map<java.lang.String , java.lang.Object> */ @RequestMapping(value = "/uploadFile", produces = "application/json;charset=UTF-8") public Map<String, Object> fileUpload(@RequestParam("file") MultipartFile multipartFile) { ResponseBean responseBean = new ResponseBean(); if (multipartFile != null) { String realName = multipartFile.getOriginalFilename(); // 原始文件名 String suffix = FileUploadUtils.fileSuffix(realName); // 文件名后缀 String tmpFileName = FileUploadUtils.createTmpFileName(suffix); // 生成保证不重复的临时文件名 if (multipartFile.getSize() > FILE_SIZE_MAX) { responseBean.putError("上传失败:文件大小不得超过20MB"); return responseBean.getResponseMap(); } File tmpFile = new File(WebConstant.FILE_STORAGE_ROOT,tmpFileName); try { multipartFile.transferTo(tmpFile); // 写入本地 responseBean.putData("data", "/images/" + tmpFileName); } catch (IOException e) { responseBean.putError("上传失败:" + e.getMessage()); e.printStackTrace(); } } return responseBean.getResponseMap(); } }

这是一个基于Spring框架开发的文件上传处理器,它接收一个MultipartFile类型的参数,即上传的文件,然后进行处理,最终返回一个包含上传结果的ResponseBean对象。其中,文件大小限制为20MB,超过限制则返回上传失败的信息;上传成功后,会将文件写入到本地,并将其访问路径存储到ResponseBean中返回。

相关推荐

<?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.de.debook.mapper.CategoryMapper"> <resultMap id="BaseResultMap" type="com.de.debook.entity.Category"> <id column="id" jdbcType="INTEGER" property="id"/> <result column="name" jdbcType="VARCHAR" property="name"/> </resultMap> <resultMap id="StatisticsResultMap" type="com.de.debook.entity.Statistics"> <result column="name" jdbcType="VARCHAR" property="name"/> <result column="value" jdbcType="VARCHAR" property="value"/> </resultMap> <sql id="Base_Column_List"> id, name </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from category where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from category where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.de.debook.entity.Category"> insert into category (id, name) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.de.debook.entity.Category"> insert into category <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="name != null"> name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.de.debook.entity.Category"> update category <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.de.debook.entity.Category"> update category set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <select id="selectAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from category order by id asc </select> <select id="selectStatistics" resultMap="StatisticsResultMap"> SELECT t1.name as name, COUNT(*) as value FROM category t1, debook t2 WHERE t1.id = t2.category_id GROUP BY t1.id order by t1.id asc </select> </mapper>

<?xml version="1.0" encoding="UTF-8"?> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.5</version> <relativePath/> <groupId>com.de</groupId> <artifactId>debook</artifactId> <version>0.0.1-SNAPSHOT</version> <name>debook</name> <description>Demo project for Spring Boot</description> <java.version>1.8</java.version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> </dependencies> <build> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </build>

最新推荐

recommend-type

概率论与数理统计试卷三套(含答案)

2020-2021年概率论与数理统计试卷
recommend-type

“人力资源+大数据+薪酬报告+涨薪调薪”

人力资源+大数据+薪酬报告+涨薪调薪,在学习、工作生活中,越来越多的事务都会使用到报告,通常情况下,报告的内容含量大、篇幅较长。那么什么样的薪酬报告才是有效的呢?以下是小编精心整理的调薪申请报告,欢迎大家分享。相信老板看到这样的报告,一定会考虑涨薪的哦。
recommend-type

伊坂幸太郎21册合集.mobi

伊坂幸太郎21册合集.mobi
recommend-type

dsdy-b4-v30003-1h.apk

dsdy-b4-v30003-1h.apk
recommend-type

Python实现基于Socket通信+PyQt5的仿QQ聊天系统项目源码(高分项目)

Python实现基于Socket通信+PyQt5的仿QQ聊天系统项目源码(高分项目)开发软件: Pycharm+ Python3.6数据库:mysql8.0 本软件基于python gui图形库pyqt5编写的仿qq,采用mysql数据库存储,socket通信(tcp协议)实现,支持多账号登录,注册,单人私聊,群聊,添加好友分组等功能。 Python实现基于Socket通信+PyQt5的仿QQ聊天系统项目源码(高分项目)客户端界面目录文件:pyqt5-qq,服务端目录文件:Tcpserver Python实现基于Socket通信+PyQt5的仿QQ聊天系统项目源码(高分项目)服务端目录结构: common:存放公共的工具类代码文件目录,主要是配置文件解析工具类,数据库操作工具类,本软件主要使用的是sqlalchemy orm数据库框架。 configfile:存放配置文件目录 dto:存放数据库表模型类代码文件 Python实现基于Socket通信+PyQt5的仿QQ聊天系统项目源码(高分项目)客户端目录结构: image,res:存放资源文件,其他文件:界面及逻辑实现源码
recommend-type

STC89C51 简单时钟

STC89C51 简单时钟,叫你从基础开始学习单片机,
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB归一化方法大比拼:5种方法,哪种最适合你的数据?

![MATLAB归一化方法大比拼:5种方法,哪种最适合你的数据?](https://www.finebi.com/wp-content/uploads/2019/11/FineBI%E8%A1%8C%E4%B8%9A%E9%A9%BE%E9%A9%B6%E8%88%B1-1024x510.png) # 1. MATLAB归一化概述 归一化是一种数据预处理技术,用于将数据缩放到特定范围内,从而消除不同特征之间的尺度差异。在MATLAB中,有各种归一化方法可用于不同类型的数据和应用程序。 归一化的主要目的是: - 提高模型的训练效率和准确性,通过消除特征之间的尺度差异,使模型能够更有效地学习
recommend-type

failed to register layer: ApplyLayer exit status 1 stdout: stderr: archive/tar: invalid tar header

很抱歉听到这个问题。这个错误通常是由于Docker镜像损坏或Docker存储库中缺少所需的图层引起的。您可以尝试以下几种方法来解决这个问题: 1. 清理Docker镜像和容器:使用命令“docker system prune”清理不再使用的Docker对象。 2. 检查Docker存储库:确保您正在使用可靠的Docker存储库,并检查是否存在所有必需的图层。 3. 重新下载Docker镜像:如果您确定问题是由于损坏的Docker镜像引起的,则可以尝试重新下载Docker镜像。 4. 更新Docker版本:如果您使用的是旧版Docker,则可能会出现此问题。尝试更新到最新版本的Docke
recommend-type

Linux系统常用操作命令大全手册

附件是Linux系统常用操作命令大全手册,是 markdown格式,其中覆盖了Linux系统管理、文件操作、网络配置等多个方面,都是日常工作中非常常用的命令,欢迎大家下载学习使用!