springboot2接收前端传的base64格式图片数据,转成图片

参考:https://blog.csdn.net/zmx729618/article/details/78038764
@PostMapping("/base64Upload")
public AppResult uploadImage(String base64Data){
    log.info("==上传图片==");
    log.info("==接收到的数据=="+base64Data);


    String dataPrix = ""; //base64格式前头
    String data = "";//实体部分数据
    if(base64Data==null||"".equals(base64Data)){
        return AppResultBuilder.buildFailedResult("上传失败,上传图片数据为空","401");
    }else {
        String [] d = base64Data.split("base64,");//将字符串分成数组
        if(d != null && d.length == 2){
            dataPrix = d[0];
            data = d[1];
        }else {
            return AppResultBuilder.buildFailedResult("上传失败,数据不合法","401");
        }
    }
    String suffix = "";//图片后缀,用以识别哪种格式数据
    //data:image/jpeg;base64,base64编码的jpeg图片数据
    if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){
        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 {
        return AppResultBuilder.buildFailedResult("上传图片格式不合法","401");
    }
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    String tempFileName=uuid+suffix;
    String imgFilePath = "G:\\Images\\"+tempFileName;//新生成的图片
    BASE64Decoder decoder = new BASE64Decoder();
    try {
        //Base64解码
        byte[] b = decoder.decodeBuffer(data);
        for(int i=0;i 
 

你可能感兴趣的:(spring,boot)