1. 程式人生 > >阿里雲物件儲存(OSS)使用小結

阿里雲物件儲存(OSS)使用小結

本文為使用OSS物件儲存小結,無廣告之嫌。

一.建立javaOSS上傳工具類

需要匯入的jar包在網站有,需要注意的是,httpclient.jar和httpcore.jar的版本需要保持一致,不然會上傳出錯。slf4j.jar 系列的也需要保持一致,上程式碼。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
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.OSSObject;
import org.apache.log4j.Logger;
/**
 * 
* @ClassName: OSSUpload
* @Description: OSS檔案上傳工具類
* @author shadow
* @date 2018年8月16日 上午10:04:38
 */
public class OSSUpload {
    static Logger logger = Logger.getLogger(OSSUpload.class);

    // endpoint是訪問OSS的域名。如果您已經在OSS的控制檯上 建立了Bucket,請在控制檯上檢視域名。
    // 如果您還沒有建立Bucket,endpoint選擇請參看文件中心的“開發人員指南 > 基本概念 > 訪問域名”,
    // 連結地址是:https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html?spm=5176.docoss/user_guide/endpoint_region
    // endpoint的格式形如“http://oss-cn-hangzhou.aliyuncs.com/”,注意http://後不帶bucket名稱,
    // 比如“http://bucket-name.oss-cn-hangzhou.aliyuncs.com”,是錯誤的endpoint,請去掉其中的“bucket-name”。
    //如果使用是阿里雲伺服器,則可以使用 oss-cn-xxxxxxx-internal.aliyuncs.com 進行內網上傳
    //private static String endpoint = "oss-cn-xxxxxxx-internal.aliyuncs.com";
    private static String endpoint = "oss-cn-xxxxxxx.aliyuncs.com";

    // accessKeyId和accessKeySecret是OSS的訪問金鑰,您可以在控制檯上建立和檢視,
    // 建立和檢視訪問金鑰的連結地址是:https://ak-console.aliyun.com/#/。
    // 注意:accessKeyId和accessKeySecret前後都沒有空格,從控制檯複製時請檢查並去除多餘的空格。
    private static String accessKeyId = "你的keyId";
    private static String accessKeySecret = "你的KeySecret";

    // Bucket用來管理所儲存Object的儲存空間,詳細描述請參看“開發人員指南 > 基本概念 > OSS基本概念介紹”。
    // Bucket命名規範如下:只能包括小寫字母,數字和短橫線(-),必須以小寫字母或者數字開頭,長度必須在3-63位元組之間。
    private static String bucketName = "你的bucketName";

   
    /**
     * 
    * @Title: putObjectByByte
    * @Description: 上傳檔案
    * @param @param filePath 檔案路徑,需要建立次級目錄直接拼接,OSS會根據路徑自動建立 ,如 aaa/bbb/ccc.jpg 
    * 				如果不存在aaa或bbb則OSS會自動建立.命名規範如下:使用UTF-8編碼,長度必須在1-1023位元組之間,不能以“/”或者“\”字元開頭。
    * @param @param data byte[] 檔案byte流
    * @param @return    設定檔案
    * @return boolean    返回型別
    * @throws
     */
    public static void putObjectByByte(String filePath,byte[] data) {
    	OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	ossClient.putObject(bucketName, filePath, new ByteArrayInputStream(data));
    	ossClient.shutdown();
    }
    
    /**
     * 
    * @Title: deleteObject
    * @Description: 刪除檔案
    * @param @param filePath 檔案路徑
    * @return void    返回型別
    * @throws
     */
    public static void deleteObject(String filePath) {
    	OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	ossClient.deleteObject(bucketName, filePath);
    	ossClient.shutdown();
    }
    
    /**
     * 
    * @Title: putObjectByInputStream
    * @Description: 上傳檔案
    * @param @param filePath
    * @param @param inputStream  檔案流
    * @return void    返回型別
    * @throws
     */
    public static void putObjectByInputStream(String filePath,InputStream inputStream) {
    	OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	ossClient.putObject(bucketName, filePath, inputStream);
    	ossClient.shutdown();
    }
    
    /**
     * 
    * @Title: putObjectByFile
    * @Description: 上傳檔案
    * @param @param filePath
    * @param @param file    本地檔案
    * @return void    返回型別
    * @throws
     */
    public static void putObjectByFile(String filePath,File file) {
    	OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	ossClient.putObject(bucketName, filePath, file);
    	ossClient.shutdown();
    }
    /**
     * 
    * @Title: downloadObjectToStringBuilder
    * @Description: 下載檔案-流式下載
    * @param @param filePath
    * @param @return    設定檔案
    * @return StringBuilder    返回型別
    * @throws
     */
    public static StringBuilder downloadObjectToStringBuilder(String filePath) {
    	OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	StringBuilder objectContent = null;
        try {
           OSSObject ossObject = ossClient.getObject(bucketName, filePath);
           InputStream inputStream = ossObject.getObjectContent();
           objectContent = new StringBuilder();
           BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                objectContent.append(line);
            }
            inputStream.close();
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return objectContent;
    }

    /**
     * 
    * @Title: downloadObjectToFile
    * @Description: 下載檔案到本地
    * @param @param ossFilePath oss上的檔案路徑
    * @param @param newFilePath 本地檔案路徑
    * @return void    返回型別
    * @throws
     */
    public static void downloadObjectToFile(String ossFilePath,String newFilePath) {
    	OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    	ossClient.getObject(new GetObjectRequest(bucketName, ossFilePath), new File(newFilePath));
    	ossClient.shutdown();
    }
}

如果不關掉apache.http日誌的debug列印,每次上傳都會打印出二進位制字串,非常多,非常耗日誌儲存,也影響除錯。在日誌配置檔案中新增 ,將列印等級變成INFO即可。

<logger name="org.apache.http" level="INFO"/>