前言
在使用SpringCloud的feign组件过程中, 我们想传递一个文件到服务提供者. 但是我们只有byte[], 这是就需要手动创建MultipartFile
实现接口MultipartFile
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
public class GYMultipartFile implements MultipartFile{
private String contentType;
private String originalFilename;
private String name;
private byte[] imgContent;
public GYMultipartFile(String name, String originalFilename, String contentType, byte[] imgContent){
this.imgContent = imgContent;
this.name = name;
this.originalFilename = originalFilename;
this.contentType = contentType;
}
@Override
public String getName() {
return name;
}
@Override
public String getOriginalFilename(){
return originalFilename;
}
@Override
public String getContentType(){
return contentType;
}
@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
@SuppressWarnings("resource")
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
}
注意事项
- 上面的name必须填写正确, name表示这个文件在表单中的名字
网友评论