ToB企服应用市场:ToB评测及商务社交产业平台

标题: 实现 文件上传【头像/图片】 [打印本页]

作者: 圆咕噜咕噜    时间: 2024-8-23 15:15
标题: 实现 文件上传【头像/图片】
实现 文件上传【头像/图片】

浏览器---->后端服务----->阿里云OSS
工具类
  1. @Data
  2. @AllArgsConstructor
  3. @Slf4j
  4. public class AliOssUtil {
  5.     private String endpoint;
  6.     private String accessKeyId;
  7.     private String accessKeySecret;
  8.     private String bucketName;
  9.     /**
  10.      * 文件上传
  11.      *
  12.      * @param bytes
  13.      * @param objectName
  14.      * @return
  15.      */
  16.     public String upload(byte[] bytes, String objectName) {
  17.         // 创建OSSClient实例。
  18.         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  19.         try {
  20.             // 创建PutObject请求。
  21.             ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
  22.         } catch (OSSException oe) {
  23.             System.out.println("Caught an OSSException, which means your request made it to OSS, "
  24.                     + "but was rejected with an error response for some reason.");
  25.             System.out.println("Error Message:" + oe.getErrorMessage());
  26.             System.out.println("Error Code:" + oe.getErrorCode());
  27.             System.out.println("Request ID:" + oe.getRequestId());
  28.             System.out.println("Host ID:" + oe.getHostId());
  29.         } catch (ClientException ce) {
  30.             System.out.println("Caught an ClientException, which means the client encountered "
  31.                     + "a serious internal problem while trying to communicate with OSS, "
  32.                     + "such as not being able to access the network.");
  33.             System.out.println("Error Message:" + ce.getMessage());
  34.         } finally {
  35.             if (ossClient != null) {
  36.                 ossClient.shutdown();
  37.             }
  38.         }
  39.         //文件访问路径规则 https://BucketName.Endpoint/ObjectName
  40.         StringBuilder stringBuilder = new StringBuilder("https://");
  41.         stringBuilder
  42.                 .append(bucketName)
  43.                 .append(".")
  44.                 .append(endpoint)
  45.                 .append("/")
  46.                 .append(objectName);
  47.         log.info("文件上传到:{}", stringBuilder.toString());
  48.         return stringBuilder.toString();
  49.     }
  50. }
复制代码
代码实现


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4