现在有个需求是接收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) Mapuploads(@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