base64转MultipartFile
final String[] base64Array = file.split(",");
String dataUir, data;
if (base64Array.length > 1) {
dataUir = base64Array[0];
data = base64Array[1];
} else {
//根据你base64代表的具体文件构建
dataUir = "data:image/jpg;base64";
data = base64Array[0];
}
MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
Base64ToMultipartFile.class
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];
// image 内容类型
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 "param_" + System.currentTimeMillis();
}
@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 InputStream 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);
}
}
}
HttpClient发起multipartfile/form-data类型请求
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//设置编码格式
builder.setCharset(Charset.forName("UTF8"));
//设置请求体的参数
//把文件放到请求体中
for (MultipartFile file : files) {
builder.addBinaryBody("files", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
}
//构建请求实体
HttpEntity entity = builder.build();
// 创建Post方式请求
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
//发送请求
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
//状态码
// int statusCode = httpResponse.getStatusLine().getStatusCode();
//msg
// String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
//data
responseBody = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
写到最后(分享呕心沥血好文👇)