赞
踩
最近做了一个h5人脸采集demo,后端调用百度人脸检测API对图片质量进行把控,图片参数可以是base64类型或者URL形式。前端把图片压缩然后转为base64传回后端,后端进行质量检测合格后把base64转为MultipartFile上传到文件服务器。
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 "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 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);
}
}
}
使用
final String[] base64Array = base64.split(",");
// 判断图片是否符合要求 略
checkImageQuality
// base64转为流
String dataUir = base64Array[0];
String data = base64Array[1];
MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。