美文网首页
图片由base64转为链接形式

图片由base64转为链接形式

作者: yunmuzhou丶 | 来源:发表于2018-12-11 16:54 被阅读0次

base64的图片格式在存储时是很占空间的,所以上传服务器后保存图片链接是个很不错的选择;代码如下:

    public String uploadImg(String baseImg){
        String url = "";
        try {
            String rootPath = "";
            String path = "";
            String random = "";
            try {
                //对于base64格式的图片,要去掉开头的部分
                int dex = baseImg.indexOf("base64,");
                baseImg = baseImg.substring(dex + 7);
                //将图片信息转换为字节数组
                byte[] arr = Base64Decoder.decodeToBytes(baseImg);
                random = UUID.randomUUID().toString() + ".jpg";
                String root = PathKit.getWebRootPath();
                path = "/upload/";
                rootPath = root + path;
                File targetDir = new File(rootPath);
                if (!targetDir.exists()) {
                    targetDir.mkdirs();
                }
                OutputStream out = new FileOutputStream(rootPath + random);
                //循环写出,确保文件写完
                for (int i = 0; i < arr.length; i++) {
                    out.write(arr[i]);// 逐字节写文件
                }
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //测试地址(地址自定义)
            url = "http://localhost:8080/kd_admin/upload/"+ random;
            
        } catch (Exception e) {
            url = null;
            e.printStackTrace();
        }
        return url;
    }

相关文章

网友评论

      本文标题:图片由base64转为链接形式

      本文链接:https://www.haomeiwen.com/subject/dnjehqtx.html