阿里云OSS对象存储(文件上传与下载)宝宝级教程

1、注册自己的阿里云账号

2、登录账号以后,进入主页面搜索“对象存储OSS

然后可以看到如下界面在这里插入图片描述

  • 立即购买,自己学习使用可以选择购买最小的存储空间,半年即可
  • 管理控制台,购买了存储空间以后可以OSS控制台
    如果不购买依旧可以使用OSS,但是会按量付费,建议购买。

3、进入控制台

进入以后,选择左侧菜单栏的Bucket列表这一项,然后点击创建Bucket
在这里插入图片描述

  • Bucket的名字需要全局唯一,地域建议选择距离自己近的地域,提高访问速度,其他选项选择默认选项即可,最后点击确定。

4、进入自己刚创建好的Bucket

点击你刚刚创建好的Bucket的名字,进入Bucket管理界面,然后选择文件管理,就可以上传文件了

  • 关于图片,如果需要上传图片,并且在你的HTML页面通过<img>标签访问,那么你需要在权限管理中将你的Bucket ACL设置为公共读,此时你图片详情里面的URL会发生更改,这时你就可以在你的页面看到图片了。
    在这里插入图片描述

5、Java整合文件上传下载

本人已经写好了基本文件上传的工具类,包含文件的上传下载与删除,如果需要其他功能,可以自行查阅API。

  • 使用此工具类需要提前导入相应的依赖,依赖坐标如下
	   <!--阿里云OOS SDK依赖-->
       <dependency>
           <groupId>com.aliyun.oss</groupId>
           <artifactId>aliyun-sdk-oss</artifactId>
           <version>3.15.0</version>
       </dependency>
  • 工具类如下,工具类的名字为OSSUploadFileUtils,如果需要自己取名字,那么工具类中downloadFile(String filename,String filePath)方法需要更改。
ossClient.getObject(new GetObjectRequest(bucketName, filename).
                            <GetObjectRequest>withProgressListener(new OSSUploadFileUtils()),
                    new File(filePath));

其中的new OSSUploadFileUtils()改为new你自己的类名

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

import java.io.*;

/**
 * @author c先生
 * @date 2022年09月07日 下午 8:10:51
 * @describe
 */

public class OSSUploadFileUtils implements ProgressListener {
    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    private static final String accessKeyId = "LTAI5tEWrVLBY1KKw6qMjn4J";
    private static final String accessKeySecret = "NfqXkkbwJ8kaPJl8TLX6eiS9cbCBW3";
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 填写Bucket名称,例如examplebucket。
    private static final String bucketName = "lx-dmeo";

    /*上传下载进度条参数*/
    private long bytesRead = 0;
    private long totalBytes = -1;
    private boolean succeed = false;


    /**
     * 通过InputStream输入流的方式上次文件
     * @param fileName  上传到服务器的文件名
     * @param inputStream  文件的输入流
     */
    public static void uploadFile(String fileName,InputStream inputStream){

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);
        } 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());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 从阿里云下载文件到本地
     * @param filename  阿里云对象存储的文件的名字
     * @param filePath  下载到本地的路径,路径包括文件名字
     * @return
     * @throws IOException
     */
    public static void downloadFile(String filename,String filePath) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
            // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, filename).
                            <GetObjectRequest>withProgressListener(new OSSUploadFileUtils()),
                    new File(filePath));
        } 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());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 上传下载进度条的方法
     * @param progressEvent
     */
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                System.out.println("开始下载......");
                break;
            case RESPONSE_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                System.out.println(this.totalBytes + " bytes in total will be downloaded to a local file");
                break;
            case RESPONSE_BYTE_TRANSFER_EVENT:
                this.bytesRead += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int)(this.bytesRead * 100.0 / this.totalBytes);
                    System.out.println(bytes + " bytes have been read at this time, 下载进度: " +
                            percent + "%(" + this.bytesRead + "/" + this.totalBytes + ")");
                } else {
                    System.out.println(bytes + " bytes have been read at this time, download ratio: unknown" +
                            "(" + this.bytesRead + "/...)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                System.out.println("下载成功! " + this.bytesRead + " bytes have been transferred in total");
                break;
            case TRANSFER_FAILED_EVENT:
                System.out.println("下载失败! " + this.bytesRead + " bytes have been transferred");
                break;
            default:
                break;
        }
    }
    public boolean isSucceed() {
        return succeed;
    }

    /**
     * 删除云端文件
     * @param fileName  要删除的文件名字
     */
    public static void deleteFile(String fileName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录,目录必须为空。
            ossClient.deleteObject(bucketName, fileName);
        } 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());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HelloWorld高级工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值