赞
踩
需求:接收base64编码的文件,然后上传到文件服务器。
思路:首先将base64转为MultipartFile类型,然后通过feign调用将文件上传至服务器
代码如下:
- @RequestMapping(method = RequestMethod.POST, value = "/doc/file/uploadForAPI",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
- Response docUpload(@RequestPart("file") MultipartFile file,
- @RequestParam("appCode") String appCode,
- @RequestParam("fileProp") String fileProp,
- @RequestParam(value = "folderName",required = false) String folderName) throws Exception;
base64转成对应的MultipartFile,代码如下:
- package com.*.product.evidence.storage.model;
-
- 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
- * @date 2022/12/06 16:40
- * @description 转换base64为文件流
- */
- public class Base64ToMultipartFile implements MultipartFile {
-
- private final byte[] fileContent;
-
- private final String name;
- private final String extension;
- private final String contentType;
-
- private final String originalFilename;
-
- /**
- * @param base64
- * @param dataUri 格式类似于: data:image/png;base64
- */
- public Base64ToMultipartFile(String base64, String dataUri, String name, String originalfilename) {
- this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
- this.extension = dataUri.split(";")[0].split("/")[1];
- this.contentType = dataUri.split(";")[0].split(":")[1];
- this.originalFilename = originalfilename;
- this.name = name;
- }
-
- /**
- * 【重要】必须与请求接收方参数名称一致,否则找不到参数
- * @return
- */
- @Override
- public String getName() {
- return this.name;
- }
-
- @Override
- public String getOriginalFilename() {
- return originalFilename;
- }
-
- @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);
- }
- }
-
- }
调试后文件服务器报错提示找不到请求参数“file”,经过长时间的排查发现重写的Base64ToMultipartFile类的getName()方法必须返回和接收参数同名的值,即file,否则feign的接收方无法收到对应的参数。
对应的实例化方法:
MultipartFile file = new Base64ToMultipartFile(data, dataUri, "file", entity.getFileName());
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。