废话不多说,直接上干货
废话不多说,直接上干货
废话不多说,直接上干货
MultipartFile转换为byte[ ]
public void convertByte(MultipartFile file) {
String fileName = file.getOriginalFilename();
// 上传文件为空
if (StringUtils.isEmpty(fileName)) {
throw new RuntimeException("上传文件为空");
}
byte[] fileBytes = null;
try {
fileBytes = file.getBytes();
} catch (IOException e) {
log.error("-================= 文件字节转换异常", e);
throw new RuntimeException("文件字节转换异常");
}
}
byte[ ]转换为MultipartFile
这个地方用到了MockMultipartFile这个玩意儿,MockMultipartFile是Spring Framework中提供的一个测试工具类,可以用于模拟MultipartFile对象,他是属于spring-test
包里的东西,所以要引入以下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.9</version>
</dependency>
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
public void convertMultipartFile(MultipartFile file) {
byte[] fileBytes = redisTemplate.opsForValue().get(fileKey);
if (fileBytes == null) {
log.error("-======================== 获取文件异常");
throw new RuntimeException("获取文件异常");
}
String fileName = "fileName";
MediaType mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
MultipartFile convert = new MockMultipartFile(fileName, fileName, mediaType.toString(), fileBytes);
}
java.io.File转换为MultipartFile
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileToMultipartFileConverter {
public MultipartFile convert(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(
file.getName(), // 文件名
file.getName(), // 原始文件名
"application/vnd.ms-excel", // 文件类型
inputStream // 文件内容
);
return multipartFile;
}
}