1、依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>aliyun-oss-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

2、配置yml

在这里插入图片描述

endpoint

在这里插入图片描述

access-key
secret-key

在这里插入图片描述

bucketName:

在这里插入图片描述

3、创建实体类

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OSS {
    @Value("${alibaba.cloud.oss.endpoint}")
    private String endPoint;
    @Value("${alibaba.cloud.access-key}")
    private String accessKeyId;
    @Value("${alibaba.cloud.secret-key}")
    private String accessKeySecret;
    @Value("${alibaba.cloud.bucketName}")
    private String bucketName;
}

4、Service层

@Service("/LogoService")
public class LogoServiceImpl implements LogoService {

    @Autowired
    private OSS oss;

    @Override
    public String addLogo(MultipartFile brandLogoUrl) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = oss.getEndPoint();
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = oss.getAccessKeyId();
        String accessKeySecret = oss.getAccessKeySecret();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = oss.getBucketName();
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        // 根据当前日期创建文件夹
        String originalFilename = brandLogoUrl.getOriginalFilename();
        LocalDate localDate = LocalDate.now();
        String objectName = localDate + "/" + originalFilename;
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
//        String filePath= "D:\\localpath\\examplefile.txt";

        // 创建OSSClient实例。
        com.aliyun.oss.OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 接收返回的url
        String url = "";
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, brandLogoUrl.getInputStream());
            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            // 获取文件url
            // url过期时间
            Date date = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);
            url = ossClient.generatePresignedUrl(bucketName, objectName, date).toString();
            return url;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}

5、调用

String url = logoService.addLogo(brandLogoUrl);
<input type="file" name="brandLogoUrl" class="form-control" placeholder="请上传品牌Logo图标"/>

使用后返回上传文件的URL

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐