开发中一般会遇到,前端上传富文本数据,这里主要讲如何处理富文本中的图片数据
一、从富文本中提取图片的base64字符串集合
public static List<String> getImgStr(String content) {
List<String> list = new ArrayList<>();
String img = "";
Pattern p_image;
Matcher m_image;
// String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(content);
while (m_image.find()) {
// 得到<img />数据
img = m_image.group();
// 匹配<img>中的src数据
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
list.add(m.group(1));
}
}
return list;
}
二、base64字符串集合 转成 MultipartFile[]
MultipartFile:多部件解析器,用来实现文件上传的,需要转换成这个
public static MultipartFile[] uploadFile(List<String> base64) {
List<MultipartFile> dataList = new ArrayList<>();
for (String s : base64) {
final String[] base64Array = s.split(",");
String dataUir, data;
if (base64Array.length > 1) {
dataUir = base64Array[0];
data = base64Array[1];
} else {
dataUir = "data:image/jpg;base64";
data = base64Array[0];
}
boolean base64Encode = Base64Utils.isBase64Encode(data);
if (!base64Encode){
continue;
}
dataList.add(new Base64ToMultipartFile(data, dataUir));
}
return dataList.toArray(new MultipartFile[dataList.size()]);
}
base64位的工具类。在开发编辑功能时,富文本的内容默认是图片地址而不是base64位的字符串,所以在后台需要效验下(后期追加工具类)
/**
* 效验字符串 是否是base64位
* @param base64
* @return
*/
public static boolean isBase64Encode(String base64){
if(base64.length()%4!=0){
return false;
}
String pattern = "^[a-zA-Z0-9/+]*={0,2}$";
return Pattern.matches(pattern, base64);
}
三、下载到本地
可以去网上找简单点的工具类,下面案例可能比较复杂
3.1 批量上传图片
/**
* @Description 批量上传图片
* @author wlj
**/
public static List<String> getFileUrls(MultipartFile[] files, Integer code){
// 自定义变量,拼接图片
List<String> imgUrlsList = new ArrayList<>();
//判断files数组不能为空并且长度大于0
if (files != null && files.length > 0) {
//循环获取file数组中得文件
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String fileUrl = FileUploadUtils.getUploadFile(file, code);
if (StringUtils.isNotEmpty(fileUrl)) {
imgUrlsList.add(fileUrl);
}
}
}
return imgUrlsList;
}
3.2 获取文件的下载路径
/**
* 获取文件的下载路径
* @param file
* @param code
* @return
*/
public static String getUploadFile(@RequestParam("file") MultipartFile file, Integer code) {
String uploadPath = JzConfig.root_path + UploadEnum.getEnumMap().get(code);
try {
String fileUrl = FileUploadUtils.upload(uploadPath, file, code);
return fileUrl;
} catch (IOException e) {
return "上传图片失败";
}
}
@Component
public class JzConfig {
/**
* 根路径
*/
public static String root_path = System.getProperty("user.dir") + "/static/";
}
public enum UploadEnum {
PICTURE_PRODUCT(1, "resources/3_product/"), //产品
CONTENT_PRODUCT(2, "resources/productArticle/"),
PICTURE_TAG(3, "resources/tag/"), //标签
CONTENT_ARTICLE(4, "resources/article/"), //新闻
CONTENT_INTRODUCE(5, "resources/introduce/"), //宣传
CONTENT_SCHEME(6, "resources/Scheme/"), //方案
PICTURE_DATA_PRODUCT(7, "resources/Handbook/"), //产品资料
MODEL_PRODUCT(8, "resources/product/"), //产品型号
LOGO(9, "resources/partners/"); //合作伙伴
private Integer index;
private String name;
private static Map<Integer, String> Index2name = null;
public static Map<Integer, String> getEnumMap(){
if(null == Index2name){
Index2name = new HashMap<>();
for (UploadEnum w : UploadEnum.values()) {
Index2name.put(w.getIndex(), w.getName());
}
}
return Index2name;
}
UploadEnum(Integer index, String name) {
this.index = index;
this.name = name;
}
public Integer getIndex() {
return index;
}
public String getName() {
return name;
}
}
3.3 根据文件路径上传
/**
* 根据文件路径上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @param code 业务代码
* @return 文件名称
* @throws IOException
*/
public static final String upload(String baseDir, MultipartFile file, Integer code) throws IOException {
try {
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, code);
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
3.4 MimeTypeUtils工具类 限定上传的文件格式
/**
* 媒体类型工具类
*
* @author jz
*/
public class MimeTypeUtils {
public static final String IMAGE_PNG = "image/png";
public static final String IMAGE_JPG = "image/jpg";
public static final String IMAGE_JPEG = "image/jpeg";
public static final String IMAGE_BMP = "image/bmp";
public static final String IMAGE_GIF = "image/gif";
public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};
public static final String[] FLASH_EXTENSION = {"swf", "flv"};
public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb"};
public static final String[] DEFAULT_ALLOWED_EXTENSION = {
// 图片
"bmp", "gif", "jpg", "jpeg", "png",
// word excel powerpoint
"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
// 压缩文件
"rar", "zip", "gz", "bz2",
// pdf
"pdf",
// 视频处理
"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
"asf", "rm", "rmvb","mp4"};
public static String getExtension(String prefix) {
switch (prefix) {
case IMAGE_PNG:
return "png";
case IMAGE_JPG:
return "jpg";
case IMAGE_JPEG:
return "jpeg";
case IMAGE_BMP:
return "bmp";
case IMAGE_GIF:
return "gif";
default:
return "";
}
}
}
3.5 文件上传
/**
* 文件上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @param code 业务编码
* @param allowedExtension 上传文件类型
* @return 返回上传成功的文件名
* @throws FileSizeLimitExceededException 如果超出最大大小
* @throws FileNameLengthLimitExceededException 文件名太长
* @throws IOException 比如读写文件出错时
* @throws InvalidExtensionException 文件校验异常
*/
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension, Integer code)
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
InvalidExtensionException {
FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
String fileName = extractFilename(file);
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
String pathFileName = getPathFileName(code, fileName);
return pathFileName;
}
3.6 补充:自定义文件名
/**
* 编码文件名
*/
public static final String extractFilename(MultipartFile file) {
String fileName = file.getOriginalFilename();
String extension = getExtension(file);
fileName = IdUtils.fastUUID() + "." + extension;
return fileName;
}
/**
* 获取文件名的后缀
*
* @param file 表单文件
* @return 后缀名
*/
public static final String getExtension(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (StringUtils.isEmpty(extension)) {
extension = MimeTypeUtils.getExtension(file.getContentType());
}
return extension;
}
3.6 补充:UUID工具类
/**
* ID生成器工具类
*
* @author jz
*/
public class IdUtils {
/**
* 获取随机UUID
*
* @return 随机UUID
*/
public static String randomUUID() {
return UUID.randomUUID().toString();
}
/**
* 简化的UUID,去掉了横线
*
* @return 简化的UUID,去掉了横线
*/
public static String simpleUUID() {
return UUID.randomUUID().toString(true);
}
/**
* 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 随机UUID
*/
public static String fastUUID() {
return UUID.fastUUID().toString();
}
/**
* 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 简化的UUID,去掉了横线
*/
public static String fastSimpleUUID() {
return UUID.fastUUID().toString(true);
}
/**
* 按时间生成订单编号 时间戳+随机5位数
* @return
*/
public static String createUUID(){
//time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
StringBuilder sb = new StringBuilder(dateFormat.format(new Date()));
//2021051208302599999
return sb.append(RandomUtil.randomNumbers(5)+"").toString();
}
}
3.7 补充:获取文件绝对路径
public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return desc;
3.8 补充:获取文件的相对路径
private static final String getPathFileName(Integer code, String fileName) throws IOException {
return UploadEnum.getEnumMap().get(code) + fileName;
}