java base64格式上传阿里云oss

因为本人是个菜鸡,在使用阿里云oss上传时遇到很多问题。做个笔记吧。。。大佬勿喷。

上传base64格式图片至阿里云

    public String upload(String imageString,String dir) throws Exception {
		String endpoint = "";
		String accessKeyId= "";
		String accessKeySecret = "";
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        
        // 使用前端插件时可能有前有("data:image/xxxx;base64,")
        // 获取图片格式
        String suffix = imageString.substring(11,imageString.indexOf(";"));
        // 使用插件传输产生的前缀
        String prefix = imageString.substring(0,imageString.indexOf(",") + 1);
        // 替换前缀为空
        imageString = imageString.replace(prefix,"");
        // imageString = imageString.substring(imageString.indexOf(",") + 1);
        
        Base64 base64 = new Base64();
        byte[] imageByte =  base64.decode(image);
        
        // 打包时将出现内部专用api异常
        // BASE64Decoder decoder = new BASE64Decoder();
        // byte[] imageByte = decoder.decodeBuffer(imageString);
       
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageByte);
        
        // InputStream binaryStream = serialBlob.getBinaryStream();
        // SerialBlob serialBlob = new SerialBlob(imageByte);
        // dir为图片目录
        String key= getFilename(dir,suffix);
        ossClient.putObject("bucketName", key, byteArrayInputStream);
        ossClient.shutdown();
        return key;
    }
    // 生成文件名加目录
    public String getFilename(String dir,suffix){
       	// 使用uuid生成唯一文件名
        String uuid = UUID.randomUUID().toString();
        return dir+ "/" + uuid + "." +suffix;;
    }

在这里插入图片描述

获得私有图片连接地址

  public URL getUrl(OSSClient ossClient, String objectName) throws ParseException {
		// 设置过期时间
        Date expiration =  new Date(new Date().getTime() + 3600*24*31*120);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
        // 设置过期时间。
        request.setExpiration(expiration);
        // 生成签名URL(HTTP GET请求)。
        URL signedUrl = ossClient.generatePresignedUrl(request);

        // 使用签名URL发送请求。
        Map<String, String> customHeaders = new HashMap<>();
        // 添加GetObject请求头。
        customHeaders.put("Range", "bytes=100-1000");
        OSSObject object = ossClient.getObject(signedUrl, customHeaders);
        return signedUrl;
    }
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值