一种文件和base64互转的实现
一、背景
有的时候需要将文件通过网络传输,这个时候服务端可以将文件转成base64的字符串,然后进行传输,客户端接收到后可将base64再转成文件并保存到当地
CODE
/**
* 输入流转byte或者字符串
*/
private byte[] convertStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
result.flush();
byte[] bytes = result.toByteArray();
result.close();
return bytes;
}
/**
* base64转文件
*/
private String base64ToFile(String base64, String filePath) {
try {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE);
} catch (IOException e) {
throw new RuntimeException(e);
}
return "成功";
}
/**
* 文件转base64
*/
private String fileToBase64(String filePath) {
if (StringUtils.isBlank(filePath)) {
return "文件路径不能为空";
}
try {
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 测试接口
*/
@GetMapping(value = "test/fileToBase64")
public void fileToBase64() {
ClassPathResource classPathResource = new ClassPathResource("pdf/hbzj.pdf");
String path = null;
try {
path = classPathResource.getURL().getPath().replaceFirst("/", "");
} catch (IOException e) {
throw new RuntimeException(e);
}
String base64 = fileToBase64(path);
base64ToFile(base64, path.replace("hbzj", "hbzj1"));
}
三、注意
1. 文件路径问题
- 获取文件的路径必须是绝对路径
- windows下 例如:D:/gitee/suibi/student-spring/target/classes/pdf/hbzj.pdf
2.pdf放在了resource目录下,编译的时候会把pdf同时编译,导致从base64转成文件后打不开文件
解决办法:在pom里加参数,不需要编译pdf
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 解决json文件乱码的问题-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<!-- 以下文件不编译-->
<nonFilteredFileExtensions>
<nonFilteredFileExtension>sql</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>json</nonFilteredFileExtension>
<nonFilteredFileExtension>pdf</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>