首页 > 编程知识 正文

上传Java 64格式的阿里云oss

时间:2023-05-05 11:25:37 阅读:284500 作者:1055

java base64格式上传阿里云oss 上传base64格式图片至阿里云获得私有图片连接地址

因为本人是个菜鸡,在使用阿里云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; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。