byte[]、MultipartFile、File转换一次看个够
connygpt 2024-10-21 04:52 7 浏览
目录
需求背景
当你需要将byte[]、MultipartFile、File实现互转时,无外乎以下场景:
- 保存第三方接口返回二进制流
- 前/后端文件流上传
- 微服务间调用
- 文件格式转换
正如你所需要的,通过搜索引擎筛选到我的本篇文章是因为你在开发中需要将byte[]转为MultipartFile、File格式的文件,以上需求在业务开发中是用户、客户、产品经理所喜闻乐见的,类似的文章在各大博客平台同样多如牛毛,也许你看了许多其他博主写的文章,按他们的代码按部就班去做但并没达到你需要的效果,是的,我在开发过程中也遇到了这样的痛点,因此有了这篇文章,写本文的目的意在为自己积累知识点,另外也帮助他人少走弯路。
希望我的文章能够帮您快速、高效解决您的问题,这是我莫大的荣幸。
“赠人玫瑰,手有余香” --谚语
byte[]转MultipartFile
错误示例-MockMultipartFile
首先来看一下摘自Spring官网对MockMultipartFile的一段描述:
public class MockMultipartFile extends Object implements MultipartFile Mock implementation of the MultipartFile interface. Useful in conjunction with a MockMultipartHttpServletRequest for testing application controllers that access multipart uploads.
虽然MockMultipartFile实现了MultipartFile接口,重点在于后一句对其作用的描述:用于测试访问分段上传, 所以这个类在正式环境是无法使用的,在我看来使用MockMultipartFile来实现byte[]转MockMultipartFile的博客都是误人子弟,因为你的代码不仅仅是运行在测试类中,而都是要发布在生产环境的。
maven坐标:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
<scope>test</scope>
</dependency>
byte[] testFile = new byte[1024];
InputStream inputStream = new ByteArrayInputStream(testFile);
MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
CommonsMultipartFile介绍
CommonsMultipartFile是 Spring 框架3.1版本后引入,用于与Apache Commons FileUpload 库集成的适配器。它实现了 Spring 的 MultipartFile 接口,允许你将Apache Commons FileUpload 的 FileItem 对象作为 Spring 的 MultipartFile 来使用。
CommonsMultipartFile实现
以maven的方式如何引入CommonsMultipartFile:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
实现代码:
private static MultipartFile convertByteToMultipartFile(byte[] imageBytes,String fileName) {
if (Objects.isNull(imageBytes)) {
log.error("获取微信小程序码图片信息失败,接口返回为空");
throw new CustomException("由于输入byte数组为空,导致转换为MultipartFile失败");
}
String contentType = "image/jpeg";
FileItem item;
try {
FileItemFactory factory = new DiskFileItemFactory();
item = factory.createItem("file", contentType, false, fileName);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(imageBytes.length);
OutputStream os = item.getOutputStream()) {
bos.write(imageBytes);
os.write(bos.toByteArray());
}
return new CommonsMultipartFile(item);
} catch (IOException e) {
log.error("转换微信小程序码图片信息为MultipartFile时发生错误", e);
throw new CustomException("转换过程中发生错误", e);
}
}
byte[]转File
byte[]转File的实现方式更多一些,很多第三方高质量的轮子提供了均对应的方法,无需自行实现,调用API即可,下文以HuTool``与Apache Commons lang3举例。
前置条件-获取文件byte[]
以下代码从本地读取文件并转为byte[]用于模拟业务逻辑。
/**
* 将文件内容读取到字节数组中。
*
* @param filePath 文件路径
* @return 字节数组,如果文件不存在或读取过程中发生错误,则返回null
*/
public static byte[] getFileBytes(String filePath) {
File file = new File(filePath);
// 检查文件是否存在
if (!file.exists()) {
System.out.println("文件不存在");
return null;
}
try (// 使用try-with-resources语句自动管理资源
FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel()) {
// 分配一个ByteBuffer,大小为文件的大小
ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
// 从文件通道读取数据到ByteBuffer
fileChannel.read(byteBuffer);
// 反转ByteBuffer的limit和position,使得可以通过array()方法获取数据
byteBuffer.flip();
// 返回包含文件数据的字节数组
return byteBuffer.array();
} catch (IOException e) {
// 如果发生IO异常,记录错误日志并返回null
e.printStackTrace(); // 这里假设e.printStackTrace()是日志记录的一种形式
return null;
}
}
}
以Hutool的方式
引入Hutool
以maven坐标的方式:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.26</version>
</dependency>
以Gradle的方式:
implementation 'cn.hutool:hutool-all:5.8.26'
byte[] data = getFileBytes("src/main/resources/banner.txt");
// 指定要创建的文件路径
String filePath = "/path/to/your/output/file";
// 使用HuTool将byte数组写入到文件
File file = FileUtil.writeBytes(data, filePath);
以Apache Commons IO的方式
引入Apache Commons IO
以maven坐标的形式:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.16.1</version>
</dependency>
以Gradle的形式:
implementation 'commons-io:commons-io:2.16.1'
代码实现:
public static void main(String[] args) {
try {
//业务逻辑中获取到的byte[]
byte[] fileBytes = getFileBytes("src/main/resources/banner.txt");
//目标文件
String outputFilePath = "src/main/resources/banner22.txt";
File outputFile = writeBytesToFile(outputFilePath, fileBytes);
log.error("文件写入成功,输出文件路径: {}", outputFile.getAbsolutePath());
} catch (IOException e) {
log.error("转换错误", e);
}
}
public static File writeBytesToFile(String filePath, byte[] fileBytes) throws IOException {
File outputFile = new File(filePath);
FileUtils.writeByteArrayToFile(outputFile, fileBytes);
// 返回File对象
return outputFile;
}
MultipartFile与File互转
字节数组可以转换为File,同样也可以转换为MultipartFile,那么MultipartFile与File之间的互转可以利用byte[]作为中间桥梁。
MultipartFile转File
MultipartFile接口提供了getInputStream()方法,你可以使用这个方法来读取文件内容,并将它们写入到一个新的File对象中。
public class MultipartFileToFileConverter {
public static File convert(MultipartFile multipartFile, String filePath) throws IOException {
// 检查MultipartFile是否为空
if (multipartFile == null || multipartFile.isEmpty()) {
throw new IOException("文件为空");
}
// 创建File对象
File file = new File(filePath);
// 使用try-with-resources语句自动关闭资源
try (InputStream inputStream = multipartFile.getInputStream();
FileOutputStream outputStream = new FileOutputStream(file)) {
// 将输入流中的数据写入到输出流(即文件)中
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
// 返回创建的File对象
return file;
}
}
File转MultipartFile
File转MultipartFile同样需要依赖于CommonsMultipartFile。
public class FileToMultipartFileConverter {
public static MultipartFile convert(File file) throws IOException, FileUploadException {
// 创建FileItemFactory实例
FileItemFactory factory = new DiskFileItemFactory();
// 创建一个FileItem来包装File对象
org.apache.commons.fileupload.FileItem fileItem = factory.createItem(
"file", // 表单字段名,可以自定义
"application/octet-stream", // 内容类型
true, // 是否使用临时文件存储上传的数据
file.getName() // 文件名
);
// 将File对象的内容写入到FileItem中
fileItem.write(new File(fileItem.getName()));
// 使用CommonsMultipartFile来包装FileItem
return new DiskFileItem(fileItem).getStoreLocation();
}
}
星空不问赶路人,岁月不负有心人。
作者:FirstMrRight
链接:https://juejin.cn/post/7382386471272202275
相关推荐
- 3分钟让你的项目支持AI问答模块,完全开源!
-
hello,大家好,我是徐小夕。之前和大家分享了很多可视化,零代码和前端工程化的最佳实践,今天继续分享一下最近开源的Next-Admin的最新更新。最近对这个项目做了一些优化,并集成了大家比较关注...
- 干货|程序员的副业挂,12个平台分享
-
1、D2adminD2Admin是一个完全开源免费的企业中后台产品前端集成方案,使用最新的前端技术栈,小于60kb的本地首屏js加载,已经做好大部分项目前期准备工作,并且带有大量示例代码,助...
- Github标星超200K,这10个可视化面板你知道几个
-
在Github上有很多开源免费的后台控制面板可以选择,但是哪些才是最好、最受欢迎的可视化控制面板呢?今天就和大家推荐Github上10个好看又流行的可视化面板:1.AdminLTEAdminLTE是...
- 开箱即用的炫酷中后台前端开源框架第二篇
-
#头条创作挑战赛#1、SoybeanAdmin(1)介绍:SoybeanAdmin是一个基于Vue3、Vite3、TypeScript、NaiveUI、Pinia和UnoCSS的清新优...
- 搭建React+AntDeign的开发环境和框架
-
搭建React+AntDeign的开发环境和框架随着前端技术的不断发展,React和AntDesign已经成为越来越多Web应用程序的首选开发框架。React是一个用于构建用户界面的JavaScrip...
- 基于.NET 5实现的开源通用权限管理平台
-
??大家好,我是为广大程序员兄弟操碎了心的小编,每天推荐一个小工具/源码,装满你的收藏夹,每天分享一个小技巧,让你轻松节省开发效率,实现不加班不熬夜不掉头发,是我的目标!??今天小编推荐一款基于.NE...
- StreamPark - 大数据流计算引擎
-
使用Docker完成StreamPark的部署??1.基于h2和docker-compose进行StreamPark部署wgethttps://raw.githubusercontent.com/a...
- 教你使用UmiJS框架开发React
-
1、什么是Umi.js?umi,中文可发音为乌米,是一个可插拔的企业级react应用框架。你可以将它简单地理解为一个专注性能的类next.js前端框架,并通过约定、自动生成和解析代码等方式来辅助...
- 简单在线流程图工具在用例设计中的运用
-
敏捷模式下,测试团队的用例逐渐简化以适应快速的发版节奏,大家很早就开始运用思维导图工具比如xmind来编写测试方法、测试点。如今不少已经不少利用开源的思维导图组件(如百度脑图...)来构建测试测试...
- 【开源分享】神奇的大数据实时平台框架,让Flink&Spark开发更简单
-
这是一个神奇的框架,让Flink|Spark开发更简单,一站式大数据实时平台!他就是StreamX!什么是StreamX大数据技术如今发展的如火如荼,已经呈现百花齐放欣欣向荣的景象,实时处理流域...
- 聊聊规则引擎的调研及实现全过程
-
摘要本期主要以规则引擎业务实现为例,陈述在陌生业务前如何进行业务深入、调研、技术选型、设计及实现全过程分析,如果你对规则引擎不感冒、也可以从中了解一些抽象实现过程。诉求从硬件采集到的数据提供的形式多种...
- 【开源推荐】Diboot 2.0.5 发布,自动化开发助理
-
一、前言Diboot2.0.5版本已于近日发布,在此次发布中,我们新增了file-starter组件,完善了iam-starter组件,对core核心进行了相关优化,让devtools也支持对IAM...
- 微软推出Copilot Actions,使用人工智能自动执行重复性任务
-
IT之家11月19日消息,微软在今天举办的Ignite大会上宣布了一系列新功能,旨在进一步提升Microsoft365Copilot的智能化水平。其中最引人注目的是Copilot...
- Electron 使用Selenium和WebDriver
-
本节我们来学习如何在Electron下使用Selenium和WebDriver。SeleniumSelenium是ThoughtWorks提供的一个强大的基于浏览器的开源自动化测试工具...
- Quick 'n Easy Web Builder 11.1.0设计和构建功能齐全的网页的工具
-
一个实用而有效的应用程序,能够让您轻松构建、创建和设计个人的HTML网站。Quick'nEasyWebBuilder是一款全面且轻巧的软件,为用户提供了一种简单的方式来创建、编辑...
- 一周热门
- 最近发表
- 标签列表
-
- kubectlsetimage (56)
- mysqlinsertoverwrite (53)
- addcolumn (54)
- helmpackage (54)
- varchar最长多少 (61)
- 类型断言 (53)
- protoc安装 (56)
- jdk20安装教程 (60)
- rpm2cpio (52)
- 控制台打印 (63)
- 401unauthorized (51)
- vuexstore (68)
- druiddatasource (60)
- 企业微信开发文档 (51)
- rendertexture (51)
- speedphp (52)
- gitcommit-am (68)
- bashecho (64)
- str_to_date函数 (58)
- yum下载包及依赖到本地 (72)
- jstree中文api文档 (59)
- mvnw文件 (58)
- rancher安装 (63)
- nginx开机自启 (53)
- .netcore教程 (53)