1.引入spring依赖
//引入spring-test依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.8</version>
</dependency>
2.写方法
private String extracted(byte[] data) {
//创建缓存输出流
BufferedOutputStream bos = null;
// FileOutputStream流是指文件字节输出流,专用于输出原始字节流如图像数据等,其继承OutputStream类,拥有输出流的基本特性
FileOutputStream fos = null;
//创建文件对象
File file = null;
String fileName1 = "1.png";
String filePath = System.getProperty("user.dir") + File.separator + File.separator;
try {
File file1 = new File(filePath);
if (!file1.exists() && file1.isDirectory()) {
file1.mkdirs();
}
// file 进行赋值
file = new File(filePath + "\\" + fileName1);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
//将data写入文件中
bos.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//创建 MockMultipartFile 对象 MockMultipartFile implements MultipartFile
MockMultipartFile mockMultipartFile = null;
try {
//将本地的文件 转换为输出流 进行 转格式
FileInputStream inputStream = new FileInputStream(file);
//通过 MockMultipartFile 带参构造进行 创建对象 及赋值
mockMultipartFile = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),
inputStream);
} catch (IOException e) {
e.printStackTrace();
}