如何将字节数组转换为 MultipartFile [英] How to convert byte array to MultipartFile
问题描述
我以 BASE64 编码字符串(encodedBytes)的形式接收图像,并使用以下方法在服务器端解码为 byte[].
I am receiving image in the form of BASE64 encoded String(encodedBytes) and use following approach to decode into byte[] at server side.
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
现在我想使用上面获得的这个字节将其转换为 MultipartFile 吗?
Now i want to convert it into MultipartFile using this byte obtained above?
有没有办法将byte[]转换成org.springframework.web.multipart.MultipartFile??
Is there any way to convert byte[] to org.springframework.web.multipart.MultipartFile??
推荐答案
org.springframework.web.multipart.MultipartFile
是一个接口,所以首先你需要使用它的一个实现界面.
org.springframework.web.multipart.MultipartFile
is an interface so firstly you are going to need to work with an implementation of this interface.
我可以看到该接口的唯一实现是org.springframework.web.multipart.commons.CommonsMultipartFile
.可以找到该实现的 API 这里
The only implementation that I can see for that interface that you can use out-of-the-box is org.springframework.web.multipart.commons.CommonsMultipartFile
. The API for that implementation can be found here
或者 org.springframework.web.multipart.MultipartFile
是一个接口,您可以提供自己的实现并简单地包装您的字节数组.举个简单的例子:
Alternatively as org.springframework.web.multipart.MultipartFile
is an interface, you could provide your own implementation and simply wrap your byte array. As a trivial example:
/*
*<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);
}
}
这篇关于如何将字节数组转换为 MultipartFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!