百度云和阿里云实现文件上传下载和删除功能

本文档详细介绍了如何创建并配置百度云对象存储BOS实例,包括认证信息、配置文件的设置,以及客户端的创建。同时,提供了文件的上传、下载、删除和获取URL等操作的示例代码,展示了与阿里云OSS客户端的相似性。此外,代码中还包含了文件类型的HTTP头设置和内容类型判断方法。
摘要由CSDN通过智能技术生成

百度云和阿里云类似,本文以百度云为例。

创建百度云对象存储实例

1. 进入百度云官网找到对象存储BOS

在这里插入图片描述

2.创建Bucket

在这里插入图片描述

3.客户端认证信息

accessKeyId和accessKeySecret数据
在这里插入图片描述

配置BOS和OSS的配置文件:

accessKeyId和accessKeySecret为上图中认证信息中的数据。

endpoint为bucket中的官方域名。

test:
  file:
    bos:
      accessKeyId: idTest
      accessKeySecret: secretTest
      endpoint: endPointTest
    oss:
      accessKeyId: idTest
      accessKeySecret: secretTest
      endpoint: endPointTest
    bucket: test-dev
    filePath: /template/dev
    imagePath: /mnt/test-cloud/images
    

创建文件的客户端

1. 百度云客户端
public class DefaultBOSClient implements InitializingBean {

    @Value("${test.file.bos.endpoint}")
    private String endpoint;
    @Value("${test.file.bos.accessKeyId}")
    private String accessKeyId;
    @Value("${test.file.bos.accessKeySecret}")
    private String accessKeySecret;

    private BosClient client = null;

    public BosClient getDefaultBOSClient() {
        if (client == null) {
            BosClientConfiguration defalutClientConfig = DefaultBOSClientConfiguration.getDefalutClientConfig();
            defalutClientConfig.setCredentials(new DefaultBceCredentials(accessKeyId, accessKeySecret));
            defalutClientConfig.setEndpoint(endpoint);
            defalutClientConfig.setProtocol(Protocol.HTTPS);
            client = new BosClient(defalutClientConfig);
        }
        return client;
    }

    public void shutdownOSSClient() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        BosClientConfiguration defalutClientConfig = DefaultBOSClientConfiguration.getDefalutClientConfig();
        defalutClientConfig.setCredentials(new DefaultBceCredentials(accessKeyId, accessKeySecret));
        defalutClientConfig.setEndpoint(endpoint);
        defalutClientConfig.setProtocol(Protocol.HTTPS);
        client = new BosClient(defalutClientConfig);
    }
}
2. 阿里云客户端
public class DefaultOSSClient implements InitializingBean {

    @Value("${test.file.oss.endpoint}")
    private String endpoint;
    @Value("${test.file.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${test.file.oss.accessKeySecret}")
    private String accessKeySecret;

    private OSSClient client = null;

    public OSSClient getDefaultOSSClient() {
        if (client == null) {
            client = new OSSClient(endpoint, accessKeyId, accessKeySecret, DefaultOSSClientConfiguration.getDefalutClientConfig());
        }
        return client;
    }

    public void shutdownOSSClient() {
        /*if(client!=null) {
            client.shutdown();
            client = null;
        }*/
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        client = new OSSClient(endpoint, accessKeyId, accessKeySecret, DefaultOSSClientConfiguration.getDefalutClientConfig());
    }

通过文件名和桶名获取文件的URL

阿里云和百度云的操作API类似,以百度云为例:

    public String getPermissions(String bucketName, String objectName) {
        BosClient bosClient = defaultBOSClient.getDefaultBOSClient();
        boolean found = bosClient.doesObjectExist(bucketName, objectName);
        if (!found) {
            throw new CommonException("file.not.found");
        }
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
        int expirationSecond = 3600 * 1000;
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = bosClient.generatePresignedUrl(bucketName, objectName, expirationSecond);
        String urlStr = url.toString();
        defaultBOSClient.shutdownOSSClient();
        urlStr=urlStr.replace("http://","https://");
        return urlStr;
    }

文件下载

    public File download(String objectName, String bucketName) {
        File localFile = new File(path + objectName);

        BosClient defaultBOSClient = this.defaultBOSClient.getDefaultBOSClient();
        boolean found = defaultBOSClient.doesObjectExist(bucketName, objectName);
        if (!found) {
            throw new CommonException("file.not.found");
        }
        defaultBOSClient.getObject(new GetObjectRequest(bucketName, objectName), localFile);
        this.defaultBOSClient.shutdownOSSClient();
        return localFile;
    }

删除文件

    public boolean delete(String bucketName, String objectName) {
        boolean found = true;
        try {
            BosClient bosClient = defaultBOSClient.getDefaultBOSClient();
            found = bosClient.doesObjectExist(bucketName, objectName);
            if (!found) {
                throw new CommonException("file.not.found");
            }
            bosClient.deleteObject(bucketName, objectName);
            defaultBOSClient.shutdownOSSClient();
        } catch (Exception e) {
            found = false;
        }
        return found;
    }

文件上传

简单的上传, 以数据流形式上传Object(不超过5GB)。上传大文件可以使用分块上传。(目前正在研究分块上传这个功能)

    public String uploadAttachment(String bucketName, String originalFileName, String fileName, String fileType, InputStream stream) {
        String url = null;
        StringBuilder finalDispositionName = new StringBuilder();
        try {
            BosClient bosClient = defaultBOSClient.getDefaultBOSClient();
            // 初始化上传输入流  (设置上传文件时自定义Object的Http Header)
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(stream.available());
            //meta 元信息
            metadata.setContentType(getContentType(fileType));
            if(!VIDEO_MP4.equals(metadata.getContentType())){
                finalDispositionName.append("\"").append(originalFileName).append("\"");
                originalFileName = finalDispositionName.toString();
                metadata.setContentDisposition("attachment;filename=" + new String(originalFileName.getBytes("GB2312"), "ISO_8859_1"));
            }
            bosClient.putObject(bucketName, fileName, stream, metadata);
            url = bosClient.getEndpoint().toString().replaceFirst("http://", "https://" + bucketName + ".") + "/" + fileName;
            defaultBOSClient.shutdownOSSClient();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    default String getContentType(String fileType) {
        //文件名后缀
        if (".bmp".equalsIgnoreCase(fileType)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileType)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileType) || ".jpg".equalsIgnoreCase(fileType) || ".png".equalsIgnoreCase(fileType)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileType)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileType)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileType)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileType) || "pptx".equalsIgnoreCase(fileType)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileType) || "docx".equalsIgnoreCase(fileType)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileType)) {
            return "text/xml";
        }
        if (".pdf".equalsIgnoreCase(fileType)) {
            return "application/pdf";
        }
        if (".xls".equalsIgnoreCase(fileType)) {
            return "application/vnd.ms-excel";
        }
        if (".xsd".equalsIgnoreCase(fileType)) {
            return "text/xml";
        }
        String[] voice = {".avi", ".mov", ".rmvb", ".rm", ".flv", ".mp4", ".3gp",".wmv"};
        if (Arrays.asList(voice).contains(fileType)) {
            return "video/mp4";
        }
        return "application/octet-stream";
    }
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值