package com.yuantu.util;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.springframework.util.Base64Utils;
import java.io.File;
/**
* @author Administrator
* @Title: ImageBase64Upload
* @ProjectName ytmonitor
* @Description: TODO
* @date 2019/6/411:53
*/
public class ImageBase64Upload {
/**
* @Description: 文件上传
* @param // 接收base64值(请求参数);
* @return
* @MethodName
* @Author chenglong
* @date 2019/6/4 11:56
*/
public Result ImageBase64UploadFile(String base64Data){
String tempFileName="";
try {
String dataPrix = "";
String data = "";
if(base64Data == null || "".equals(base64Data)){
throw new Exception("上传失败,上传图片数据为空");
}else{
String [] d = base64Data.split("base64,");
if(d != null && d.length == 2){
dataPrix = d[0];
data = d[1];
}else{
throw new Exception("上传失败,数据不合法");
}
}
String suffix = "";
if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){//data:image/jpeg;base64,base64编码的jpeg图片数据
suffix = ".jpg";
} else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){//data:image/x-icon;base64,base64编码的icon图片数据
suffix = ".ico";
} else if("data:image/gif;".equalsIgnoreCase(dataPrix)){//data:image/gif;base64,base64编码的gif图片数据
suffix = ".gif";
} else if("data:image/png;".equalsIgnoreCase(dataPrix)){//data:image/png;base64,base64编码的png图片数据
suffix = ".png";
}else{
throw new Exception("上传图片格式不合法");
}
tempFileName = RandomUtil.generateNumString(6) + suffix;
//因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
byte[] bs = Base64Utils.decodeFromString(data);
try{
//使用apache提供的工具类操作流
FileUtils.writeByteArrayToFile(new File("D://image", tempFileName), bs);
}catch(Exception ee){
throw new Exception("上传失败,写入文件失败,"+ee.getMessage());
}
return Result.createSuccessResult(tempFileName+"文件上传成功!");
} catch (Exception ex) {
return Result.createFailResult(tempFileName+"文件上传失败,原因:"+ex.getMessage());
}
}
@Test
public void testUpload(){
String images="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSE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