【OSS】文件(实际就是Object)上传下载操作

package com.ls;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class OSSObjectSample {

	private static final String ACCESS_ID = "*************";
	private static final String ACCESS_KEY = "*********************";
	private static final String OSS_ENDPOINT = "http://oss.aliyuncs.com/";

	public static void main(String[] args) {
		//Buceket名称
		String bucketName = "saas01";
		
		//Object对象
		String key = "A/B/C/女帝.jpg";
		/*说明:
		 * 1、要满足命名规范
		 * 2、可以制定到bucket的文件夹
		 * 3、例如A/B/C/女帝.jpg则是将文件上传到bucket的文件夹A下面的文件夹B下面的文件夹C中,命名为女帝.jpg
		 * */

		String uploadFilePath = "G:/test/女帝.jpg";
		String downloadFilePath = "G:/test/photo1.jpg";

		// 使用默认的OSS服务器地址创建OSSClient对象。
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);

		client.deleteObject(bucketName, key);

		try {
			System.out.println("正在上传...");
			
			long startTime = System.currentTimeMillis();
			uploadFile(client, bucketName, key, uploadFilePath);
			long endTime = System.currentTimeMillis();
			System.out.println("上传花费时间约:" + (endTime - startTime) + " ms");

			System.out.println("正在下载...");
			long startTime_d = System.currentTimeMillis();
			downloadFile(client, bucketName, key, downloadFilePath);
			long endTime_d = System.currentTimeMillis();
			System.out.println("下载花费时间约:" + (endTime_d - startTime_d) + " ms");
			
		} catch (OSSException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("OK");
	}

	// 上传文件
	private static void uploadFile(OSSClient client, String bucketName,
			String key, String filename) throws OSSException, ClientException,
			FileNotFoundException {
		File file = new File(filename);

		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(file.length());

		InputStream input = new FileInputStream(file);
		PutObjectResult rs = client.putObject(bucketName, key, input,
				objectMeta);
		System.out.println("上传成功:" + rs.getETag());
	}

	// 下载文件
	private static void downloadFile(OSSClient client, String bucketName,
			String key, String filename) throws OSSException, ClientException {
		client.getObject(new GetObjectRequest(bucketName, key), new File(
				filename));
	}

}

你可能感兴趣的:(阿里云)