我正在接收 BASE64 编码字符串(encodedBytes)形式的图像,并使用以下方法在服务器端解码为 byte[] 。
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
现在我想使用上面获得的这个字节将其转换为 MultipartFile?
有什么方法可以将 byte[] 转换为 org.springframework.web.multipart.MultipartFile 吗?
org.springframework.web.multipart.MultipartFile
是一个接口,因此首先您需要使用该接口的实现。
我可以看到您可以开箱即用的该接口的唯一实现是org.springframework.web.multipart.commons.CommonsMultipartFile
。可以找到该实现的 APIhere https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/multipart/commons/CommonsMultipartFile.html
或者作为org.springframework.web.multipart.MultipartFile
是一个接口,您可以提供自己的实现并简单地包装您的字节数组。举一个简单的例子:
/*
*<p>
* Trivial implementation of the {@link MultipartFile} interface to wrap a byte[] decoded
* from a BASE64 encoded String
*</p>
*/
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
public BASE64DecodedMultipartFile(byte[] imgContent) {
this.imgContent = imgContent;
}
@Override
public String getName() {
// TODO - implementation depends on your requirements
return null;
}
@Override
public String getOriginalFilename() {
// TODO - implementation depends on your requirements
return null;
}
@Override
public String getContentType() {
// TODO - implementation depends on your requirements
return null;
}
@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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)