前端传base64编码,springboot框架,ssm后台转换为图片,解决损坏、打不开问题,并把图片存到本地项目及数据库

需要导入这个jia包:import sun.misc.BASE64Decoder;

/**
     * 上传头像
     * 
     * @throws FileNotFoundException
     * @throws IOException
     */
    @RequestMapping("/jieShou")
    public String GenerateImage(String tup) throws FileNotFoundException {          //tup前台传过来的base64编码
        String ret_fileName = null;
        byte[] b1 = null;
        BASE64Decoder decoder = new BASE64Decoder();
        SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();        //用的shiro框架获取当前登录用户
        // 获取跟目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists())
            path = new File("");
        File upload = new File(path.getAbsolutePath(), "/statics/userImg");
        if (!upload.exists())
            upload.mkdirs();
        String file_path = upload.getAbsolutePath();
        if (tup == null) // 图像数据为空
            return "图像数据为空";
        try {
            if (tup.indexOf("data:image/jpeg;base64,") != -1) {
                b1 = decoder.decodeBuffer(tup.replaceAll("data:image/jpeg;base64,", ""));
            } else {
                if (tup.indexOf("data:image/png;base64,") != -1) {
                    b1 = decoder.decodeBuffer(tup.replaceAll("data:image/png;base64,", ""));
                } else {
                    b1 = decoder.decodeBuffer(tup.replaceAll("data:image/jpg;base64,", ""));
                }
            }
            for (int i = 0; i < b1.length; ++i) {
                if (b1[i] < 0) {// 调整异常数据
                    b1[i] += 256;
                }
            }        
            // 生成jpeg图片,图片名称,此处可自定义,我获取的是数据库登录用户名+自增id
            ret_fileName = userEntity.getUsername() + userEntity.getUserId() + ".jpg";    
            File file = new File(file_path + "/" + ret_fileName);
            OutputStream out = new FileOutputStream(file);
            out.write(b1);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        userEntity.setUserImg(ret_fileName);
        sysUserService.updateCode(userEntity);      //更新图片  
        return ret_fileName;

    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值