将本地文件/文件流上传到阿里云OSS的方法

WxOSSClient

package com.gxs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;

public class WxOSSClient {
	private OSSClient ossClient;
	private String accessKeyId;
	private String accessKeySecret;
	private String endpoint;
	private String bucketName;

	public WxOSSClient(){}
	public WxOSSClient(String endpoint, String bucketName, String accessKeyId, String accessKeySecret) {
		this.endpoint = endpoint;
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.bucketName = bucketName;
	}

	public void init() {
		ClientConfiguration conf = new ClientConfiguration();
		conf.setMaxConnections(10);
		conf.setConnectionTimeout(5000);
		conf.setMaxErrorRetry(3);
		conf.setSocketTimeout(2000);
		ossClient = new OSSClient(endpoint, getAccessKeyId(), getAccessKeySecret(), conf);
		if (!ossClient.doesBucketExist(bucketName)) {
			ossClient.createBucket(bucketName);
		}

	}

	public void cleanUp() {
		// ossClient.
	}

	public List<String> listFiles(String parentPath) {

		List<String> fileList = new ArrayList<String>();
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");
		// 列出fun目录下的所有文件和文件夹
		listObjectsRequest.setPrefix(parentPath + "/");
		ObjectListing listing = ossClient.listObjects(listObjectsRequest);
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			fileList.add(objectSummary.getKey());
		}
		return fileList;
	}

	public List<String> listDirs(String parentPath) {
		List<String> fileList = new ArrayList<String>();
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");
		// 列出fun目录下的所有文件和文件夹
		if (parentPath != null && parentPath.length() > 0) {
			listObjectsRequest.setPrefix(parentPath + "/");
		}
		ObjectListing listing = ossClient.listObjects(listObjectsRequest);
		// 遍历所有CommonPrefix
		for (String commonPrefix : listing.getCommonPrefixes()) {
			fileList.add(commonPrefix);
		}

		return fileList;
	}

	public void uploadFile(String destFileDir, String destFileName, String sourceFilePath)
			throws FileNotFoundException {

		putObject(destFileDir, destFileName, sourceFilePath);

	}

	/**
	 * 上传Object,小文件; 
	 * @param ossClient
	 * @param bucketName
	 * @param destFileName
	 * @param sourceFilePath
	 * @throws FileNotFoundException
	 */
	public PutObjectResult putObject(String destFileDir, String destFileName, String sourceFilePath)
			throws FileNotFoundException {
		// 获取指定文件的输入流
		File file = new File(sourceFilePath);
		InputStream content = new FileInputStream(file);
		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();
		// 必须设置ContentLength
		meta.setContentLength(file.length());
		// 上传Object.
		PutObjectResult result = ossClient.putObject(bucketName, destFileDir + "/" + destFileName, content, meta);
		try {
			content.close();
		} catch (Exception e) {
		}
		return result;

	}

	public URL getOSSUrl(String destFileDir, String destFileName){
		 Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
         URL url=ossClient.generatePresignedUrl(bucketName, destFileDir + "/" + destFileName, expiration);
         System.out.println("*************"+url);
		 return url;
	}
	/**
	 * 大文件上传;
	 * @param key
	 * @param filePath
	 * @throws IOException
	 */
	public void multipartUpload(String key, String filePath) throws IOException {
		InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(bucketName,
				key);
		InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient
				.initiateMultipartUpload(initiateMultipartUploadRequest);
		// 打印UploadId
		// 设置每块为 5M
		final int partSize = 1024 * 1024 * 5;
		File partFile = new File(filePath);
		// 计算分块数目
		int partCount = (int) (partFile.length() / partSize);
		if (partFile.length() % partSize != 0) {
			partCount++;
		}
		// 新建一个List保存每个分块上传后的ETag和PartNumber
		List<PartETag> partETags = new ArrayList<PartETag>();
		for (int i = 0; i < partCount; i++) {
			// 获取文件流
			FileInputStream fis = new FileInputStream(partFile);
			// 跳到每个分块的开头
			long skipBytes = partSize * i;
			fis.skip(skipBytes);
			// 计算每个分块的大小
			long size = partSize < partFile.length() - skipBytes ? partSize : partFile.length() - skipBytes;
			// 创建UploadPartRequest,上传分块
			UploadPartRequest uploadPartRequest = new UploadPartRequest();
			uploadPartRequest.setBucketName(bucketName);
			uploadPartRequest.setKey(key);
			uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
			uploadPartRequest.setInputStream(fis);
			uploadPartRequest.setPartSize(size);
			uploadPartRequest.setPartNumber(i + 1);
			UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
			// 将返回的PartETag保存到List中。
			partETags.add(uploadPartResult.getPartETag());
			// 关闭文件
			fis.close();
		}
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

}

AliyunOSSConfigConstant 配置文件
package com.gxs;
import java.io.File;
import java.io.FileNotFoundException;

public class WxOSSClientSample {
	private static final String ENDPOINT = "";
	private static final String BUCKET_NAME = "";
	private static final String ACCESS_KEY_ID = "";
	private static final String ACCESS_KEY_SECRET = "";
	private static final String INTERNAL_ROOT = "in";
	private static final String EXTERNAL_ROOT = "ex";
	private WxOSSClient ossTools = null;

	public static void main(String[] args) {
		WxOSSClient ossTools = new WxOSSClient(ENDPOINT, BUCKET_NAME, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		ossTools.init();
		WxOSSClientSample oss = new WxOSSClientSample(ossTools);
		oss.uploadExternalFile("/Users/gg.jpg");
		//oss.uploadInternalFile("C:/Users/gxs.pdf");

		System.out.println(ossTools.listDirs(""));
		System.out.println(ossTools.listDirs(INTERNAL_ROOT));
		System.out.println(ossTools.listFiles(INTERNAL_ROOT));
		System.out.println(ossTools.listDirs(EXTERNAL_ROOT));
		System.out.println(ossTools.listFiles(EXTERNAL_ROOT));

	}

	public WxOSSClientSample(WxOSSClient ossTools) {
		this.ossTools = ossTools;
	}

	public void uploadExternalFile(String sourceFile) {
		File file = new File(sourceFile);
		try {
			ossTools.uploadFile(EXTERNAL_ROOT, file.getName(), sourceFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void uploadInternalFile(String sourceFile) {
		File file = new File(sourceFile);
		try {
			ossTools.uploadFile(INTERNAL_ROOT, file.getName(), sourceFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

}

亲测可用~

更多学习资讯,学习源码,请在耶宇星球领取

更多学习资讯,学习源码,请在耶宇星球领取
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

北顾丶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值