Java中base64转multipartFile工具类
时间: 2023-11-11 21:10:14 浏览: 179
java实现对文件的各种操作的工具类.md
由于Base64编码的数据是字符串形式的,需要将其转换为二进制数据才能保存为文件。因此,需要先将Base64编码的字符串转换为byte数组,再将byte数组转换为MultipartFile格式的文件。
以下是Java中将Base64编码的字符串转换为MultipartFile格式的工具类:
```java
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.util.Base64;
public class Base64ToMultipartFileUtil {
public static MultipartFile base64ToMultipart(String base64) throws IOException {
String[] baseStrs = base64.split(",");
byte[] bytes = new BASE64Decoder().decodeBuffer(baseStrs[1]);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
return new Base64MultipartFile(bytes, baseStrs[0]);
}
private static class Base64MultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
public Base64MultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
FileUtils.writeByteArrayToFile(dest, imgContent);
}
}
}
```
使用方法如下:
```java
MultipartFile multipartFile = Base64ToMultipartFileUtil.base64ToMultipart(base64String);
```
阅读全文