java对接天翼云OOS实现文件存储

1. 注册天翼云账户、开通对象存储、创建容器

创建容器

2. 获取AccessKeyID、SecretAccessKey

获取密钥

确定四个参数,在application.yml中填入以下配置

# 文件上传 OOS (天翼云)
oos:
  config:
    access-key: 填入之前获取的AccessKeyID
    secret-key: 填入对应密钥SecretAccessKey
    endpoint: oos-hazz.ctyunapi.cn(可以直接填此端点,不需要动)
    bucket: 容器名称

3. maven中央仓库中没有该jar包,官网下载java-oos-sdk-6.5.3.jar到本地,或者上传到maven私服下

下载链接 java-oos-sdk

4. 下载后放入项目lib目录下,在pom.xml文件中添加相关依赖

		<!--天翼云OOS-->
        <dependency>
            <groupId>cn.ctyun</groupId>
            <artifactId>ctyun-sdk-oss</artifactId>
            <version>6.5.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/oos-java-sdk-6.5.3.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>

        <dependency>
            <groupId>org.sejda.imageio</groupId>
            <artifactId>webp-imageio</artifactId>
            <version>0.1.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>

5. 添加配置类

@Data
@Component
public class OosClientConfig {

	@Value("${oos.config.access-key}")
    private String accessKey;

    @Value("${oos.config.secret-key}")
    private String secretKey;

    @Value("${oos.config.endpoint}")
    private String endpoint;

    @Value("${oos.config.bucket}")
    private String bucket;

    @Bean
    public AmazonS3 oosClient() {
        ClientConfiguration clientConfig = new ClientConfiguration();
        // 设置连接的超时时间,单位毫秒
        clientConfig.setConnectionTimeout(30 * 1000);
        // 设置 socket 超时时间,单位毫秒
        clientConfig.setSocketTimeout(30 * 1000);
        clientConfig.setProtocol(Protocol.HTTP); //设置 http
        // 设置 V4 签名算法中负载是否参与签名,关于签名部分请参看《OOS 开发者文档》
        S3ClientOptions options = new S3ClientOptions();
        options.setPayloadSigningEnabled(true);
        // 创建 client
        AmazonS3 oosClient = new AmazonS3Client(
                new PropertiesCredentials(accessKey, secretKey), clientConfig);
        // 设置 endpoint
        oosClient.setEndpoint(endpoint);
        //设置选项
        oosClient.setS3ClientOptions(options);
        return oosClient;
    }
}

6. 实现工具类,这里直接写成Service服务类,方法一样,可进行适当修改

@Log4j2
@Service
public class OosService {

    @Autowired
    private OosClientConfig oosClientConfig;

    /**
     * @Desecription: 上传文件
     */
    public String uploadFile(MultipartFile file, String fileName) {
        InputStream inputStream = null;
        String pathUrl = "";
        try {
            inputStream = file.getInputStream();
            AmazonS3 ossClient = oosClientConfig.oosClient();
            String remoteFilePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String path = dir + IdWorker.getIdStr() + suffix;
            try {
                objectMetadata.setContentLength(inputStream.available());
                // 上传文件
                log.info("开始上传文件到oss");
                log.info("bucket: " + oosClientConfig.getBucket());
                log.info("path: " + path);
                log.info("inputStream: " + inputStream);
                log.info("objectMetadata: " + objectMetadata);
                ossClient.putObject(oosClientConfig.getBucket(), path, inputStream, objectMetadata);
                // URL url = ossClient.generatePresignedUrl(new GeneratePresignedUrlRequest(oosClientConfig.getBucket(), path));
                String url = generatePresignedUrl(path);
                pathUrl = url;
            } catch (Exception e) {
                log.error("上传文件到oos失败", e);
            } finally {
                if (ossClient != null) {
                    ((AmazonS3Client) ossClient).shutdown();
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return pathUrl;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * @Desecription: 删除文件
     */
    public boolean deleteFile(String filePath, String fileName) {
        AmazonS3 ossClient = oosClientConfig.oosClient();
        String path = filePath + fileName;
        boolean exist = ossClient.doesBucketExist(oosClientConfig.getEndpoint());
        if (!exist) {
            log.error("从OSS存储删除的文件不存在,path={}", path);
            return false;
        } else {
            try {
                ossClient.deleteObject(oosClientConfig.getEndpoint(), path);
            } catch (Exception e) {
                log.error("从天翼云OSS删除文件出错,path={}", path, e);
                return false;
            } finally {
                if (ossClient != null) {
                    try {
                        ((AmazonS3Client) ossClient).shutdown();
                    } catch (AmazonClientException e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        }
    }

    /**
     * @Desecription: 获取文件下载地址 ,并设置过期时间
     */
    public String generatePresignedUrl(String fileKey) throws ParseException {
        GeneratePresignedUrlRequest request = new
                GeneratePresignedUrlRequest(oosClientConfig.getBucket(), fileKey);
/*        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date expireDate = sdf.parse("2031-01-01");
        request.setExpiration(expireDate);*/
        URL url = oosClientConfig.oosClient().generatePresignedUrl(request);
        return url.toString();
    }
}
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Spring Boot集成阿里OOS实现文件上传、下载和预览,可以参考以下步骤: 1. 引入OSS SDK依赖 在Spring Boot的pom.xml文件中添加OSS SDK依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.12.0</version> </dependency> ``` 2. 配置OSS客户端 在Spring Boot的配置文件application.properties或application.yml中配置OSS客户端: ```yaml aliyun: oss: endpoint: oss-cn-hangzhou.aliyuncs.com accessKeyId: your_access_key_id accessKeySecret: your_access_key_secret bucketName: your_bucket_name ``` 3. 实现文件上传 在Controller中实现文件上传的方法,示例代码如下: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { String fileName = file.getOriginalFilename(); // 创建OSS客户端实例 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 上传文件 ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes())); // 关闭OSS客户端 ossClient.shutdown(); return "上传成功!"; } ``` 4. 实现文件下载 在Controller中实现文件下载的方法,示例代码如下: ```java @GetMapping("/download") public void downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException { // 创建OSS客户端实例 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 下载文件 OSSObject ossObject = ossClient.getObject(bucketName, fileName); InputStream inputStream = ossObject.getObjectContent(); byte[] buffer = new byte[1024]; int len; OutputStream outputStream = response.getOutputStream(); while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } // 关闭流 outputStream.close(); inputStream.close(); // 关闭OSS客户端 ossClient.shutdown(); } ``` 5. 实现文件预览 在Controller中实现文件预览的方法,示例代码如下: ```java @GetMapping("/preview") public void previewFile(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException { // 创建OSS客户端实例 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 下载文件到本地临时文件 File tempFile = File.createTempFile("temp", fileName.substring(fileName.lastIndexOf("."))); ossClient.getObject(new GetObjectRequest(bucketName, fileName), tempFile); // 设置响应头 response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "inline;filename=" + fileName); // 输出文件流 FileInputStream inputStream = new FileInputStream(tempFile); OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } // 关闭流 outputStream.flush(); outputStream.close(); inputStream.close(); // 删除临时文件 tempFile.delete(); // 关闭OSS客户端 ossClient.shutdown(); } ``` 以上就是Spring Boot集成阿里OOS实现文件上传、下载和预览的步骤。注意:在实际开发中,需要根据具体的业务需求进行适当的修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值