1. 程式人生 > >【OSS】檔案(實際就是Object)上傳下載操作

【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));
	}

}