现在有个需求是接收base64编码的图片,然后上传到文件服务器上,由于文件服务的代码是固定的代码不能修改,所以只能适配接口。文件服务代码如下:
@FeignClient(value = \"base-files\", configuration = SpringMultipartEncoder.class) public interface UploadsClient { @PostMapping(value = \"base/file/uploads\",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},consumes = MediaType.MULTIPART_FORM_DATA_VALUE) Map<String, Object> uploads(@RequestPart(value = \"files\") MultipartFile[] files); }
所以需要把base64转成对应的MultipartFile,于是在网上找到了转换的代码
import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * @author Administrator */ public class Base64ToMultipartFile implements MultipartFile { private final byte[] fileContent; private final String extension; private final String contentType; /** * @param base64 * @param dataUri 格式类似于: data:image/png;base64 */ public Base64ToMultipartFile(String base64, String dataUri) { this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8)); this.extension = dataUri.split(\";\")[0].split(\"/\")[1]; this.contentType = dataUri.split(\";\")[0].split(\":\")[1]; } public Base64ToMultipartFile(String base64, String extension, String contentType) { this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8)); this.extension = extension; this.contentType = contentType; } @Override public String getName() { return \"files\"; } @Override public String getOriginalFilename() { return \"file_\" + System.currentTimeMillis() + \".\" + extension; } @Override public String getContentType() { return contentType; } @Override public boolean isEmpty() { return fileContent == null || fileContent.length == 0; } @Override public long getSize() { return fileContent.length; } @Override public byte[] getBytes() throws IOException { return fileContent; } @Override public ByteArrayInputStream getInputStream() throws IOException { return new ByteArrayInputStream(fileContent); } @Override public void transferTo(File file) throws IOException, IllegalStateException { try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(fileContent); } } }
调试了以后接口可以调通但是文件服务却接收不到文件,经过长时间的排查发现重写的Base64ToMultipartFile类的getName()方法必须返回和接收参数同名的值,即files,否则feign的接收方无法收到对应的参数。
Base64ToMultipartFile
来源:https://www.cnblogs.com/cott/p/16427464.html
本站部分图文来源于网络,如有侵权请联系删除。