下载OSS文件到本地(可以断点续传)

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.stereotype.Component;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.thorgene.clinical.utils.OssUtil;

public class DownOSSFile {

	public static String endpoint;
	public static String accessKeyId;
	public static String accessKeySecret;
	public static String bucketName;

	static {
		InputStream is = OssUtil.class.getResourceAsStream("/application.properties");
		Properties prop = new Properties();
		try {
			prop.load(is);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		endpoint = prop.getProperty("ali.oss.endpoint");
		accessKeyId = prop.getProperty("ali.oss.access-keyid");
		accessKeySecret = prop.getProperty("ali.oss.access-secret");
		bucketName = prop.getProperty("ali.oss.bucket-name");
	}

	public static void downFileFromOSS() throws Throwable {

		String filePath = "/tmp/aa"; // 保存目录
		String objectKey = "objectKey/";
		// 创建不同的文件夹目录
		File file = new File(filePath);
		// 判断文件夹是否存在
		if (!file.exists()) {
			// 如果文件夹不存在,则创建新的的文件夹
			file.mkdirs();
		}

		// 下载oss静态文件key
		String fileName = "thisisafilename.docx";

		// 创建OssClient对象
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取oss下载的objectName
		String objectName = objectKey + fileName;
		// 判断文件的保存路径后面是否以/结尾
		if (!filePath.endsWith("/")) {
			filePath += "/";
		}
		// 为checkpointFile命名
		String checkpointFileName = filePath + fileName.substring(0, fileName.lastIndexOf(".")) + ".ucp";

		// 下载请求
		DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, objectName);
		downloadFileRequest.setDownloadFile(filePath + fileName);// 本地下载文件名称
		downloadFileRequest.setPartSize(1 * 1024 * 1024);// 分片大小,取值范围为1B~5GB。
		downloadFileRequest.setTaskNum(10);//10个任务并发下载,默认值为1
		downloadFileRequest.setEnableCheckpoint(true);// 启动断点续传
		downloadFileRequest.setCheckpointFile(checkpointFileName);// 记录本地分片下载结果的文件。

		// 下载文件
		DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);
		// 下载成功时,会返回文件元信息。
		downloadRes.getObjectMetadata();
		// 关闭OSSClient。
		ossClient.shutdown();
	}

	public static void main(String[] args) {
		try {
			downFileFromOSS();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值