项目中有时需要通过接口传输文件,则一般通过将文件转为base64字符串进行传输。
需要引入的包:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.13</version>
</dependency>
文件转base64字符串:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
public class Test {
/**
* @Description: 文件转为base64字符串。filePath:文件路径
* @Param: [filePath]
* @return: java.lang.String
* @Date: 2020/12/25
*/
public static String fileToBase64(String filePath) throws IOException {
File file = new File(filePath);
FileInputStream inputFile = null;
byte[] buffer = null;
try {
inputFile = new FileInputStream(file);
buffer = new byte[(int) file.length()];