由于Java在和其他服务端进行通信时,会遇到编码不同的问题,所以在接受其他服务端传送的其他编码的文件时,解析就会出问题,因此直接传输base64可以有效的解决问题
public static MultipartFile getMultipartFile(String s) {
MultipartFile multipartFile = null;
//创建字符串
StringBuilder base64 = new StringBuilder("");
//判断字符串不为空
if (s != null && !"".equals(s)) {
//把字符串添加到StringBuilder中
base64.append(s);
//StringBuilder转为String[]
String[] baseStrs = base64.toString().split(",");
//创建base64
BASE64Decoder decoder = new BASE64Decoder();
//创建比特字节
byte[] b = new byte[0];
try {
//将base64转为字节数组
b = decoder.decodeBuffer(baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
}
for (int j = 0; j < b.length; ++j) {
if (b[j] < 0) {
b[j] += 256;
}
}
//转MultipartFile 这里创建一个实现MultipartFile的类,重写MultipartFile的一些方法
multipartFile = new BASE64DecodedMultipartFile(b, baseStrs[0]);
}
return multipartFile;
}
实现MultipartFile 接口对MultipartFile 的方法进行重写
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
/**
*
* @param imgContent bite数组
* @param header base64 编码
*/
public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
/**
* 设置MultipartFile的名称
* @return
*/
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + 0 * 10000 + "fileName";
}
@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 {
new FileOutputStream(dest).write(imgContent);
}
}
- THE END -
最后修改:2024年2月18日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://jiaheming.cn/2023/05/java-base64%e8%bd%acmultipartfile/

共有 0 条评论