全部產品
Search
文件中心

Object Storage Service:Java範圍下載

更新時間:Oct 19, 2024

如果僅需要檔案中的部分資料,您可以使用範圍下載,下載指定範圍內的資料。

注意事項

指定正常的下載範圍

以下代碼用於指定正常的下載範圍來下載檔案。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑,例如exampledir/exampleobject.txt。Object完整路徑中不能包含Bucket名稱。
        String objectName = "exampledir/exampleobject.txt";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        InputStream in = null;
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            // 對於大小為1000 Bytes的檔案,正常的位元組範圍為0~999。
            // 擷取0~999位元組範圍內的資料,包括0和999,共1000個位元組的資料。如果指定的範圍無效(比如開始或結束位置的指定值為負數,或指定值大於檔案大小),則下載整個檔案。
            getObjectRequest.setRange(0, 999);

            // 範圍下載。
            OSSObject ossObject = ossClient.getObject(getObjectRequest);

            // 讀取資料。
            byte[] buf = new byte[1024];
            in = ossObject.getObjectContent();
            for (int n = 0; n != -1; ) {
                n = in.read(buf, 0, buf.length);
            }
            ossObject.close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            // 資料讀取完成後,擷取的流必須關閉,否則會造成串連泄漏,導致請求無串連可用,程式無法正常工作。
            if (in != null) {
                in.close();
            }
        }
    }
}            

流式讀取一次可能無法讀取全部資料。如果您需要流式讀取64 KB的資料,請使用如下的方式多次讀取,直到讀取到64 KB或者檔案結束。詳情請參見InputStream.read

byte[] buf = new byte[1024];
InputStream in = ossObject.getObjectContent();
for (int n = 0; n != -1; ) {
    n = in.read(buf, 0, buf.length);
}
in.close();

指定異常的下載範圍

假設現有大小為1000 Bytes的Object,則指定的正常下載範圍應為0~999。如果指定範圍不在有效區間,會導致Range不生效,響應傳回值為200,並傳送整個Object的內容。請求不合法的樣本及返回說明如下:

  • 若指定了Range: bytes=500~2000,此時範圍末端取值不在有效區間,返回整個檔案的內容,且HTTP Code為200。

  • 若指定了Range: bytes=1000~2000,此時範圍首端取值不在有效區間,返回整個檔案的內容,且HTTP Code為200。

標準行為範圍下載

在請求中增加要求標頭x-oss-range-behavior:standard,則改變指定範圍不在有效區間時OSS的下載行為。假設現有大小為1000 Bytes的Object:

  • 若指定了Range: bytes=500~2000,此時範圍末端取值不在有效區間,返回500~999位元組範圍內容,且HTTP Code為206。

  • 若指定了Range: bytes=1000~2000,此時範圍首端取值不在有效區間,返回HTTP Code為416,錯誤碼為InvalidRange。

以下代碼用於標準行為範圍下載。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑,例如exampledir/exampleobject.txt。Object完整路徑中不能包含Bucket名稱。
        String objectName = "exampledir/exampleobject.txt";

        // 建立OSSClient執行個體。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 範圍末端取值不在有效區間,返回500~999位元組範圍內容,且HTTP Code為206。
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
            getObjectRequest.setRange(500, 2000);
            getObjectRequest.addHeader("x-oss-range-behavior", "standard");
            OSSObject ossObject = ossClient.getObject(getObjectRequest);
            ossObject.close();

            System.out.println("standard get " + "500~2000 "+ "statusCode:"  + ossObject.getResponse().getStatusCode());
            System.out.println("standard get " + "500~2000 " + "contentLength:" + ossObject.getResponse().getContentLength());

            // 範圍首端取值不在有效區間,以下代碼會拋出異常。返回HTTP Code為416,錯誤碼為InvalidRange。
            getObjectRequest = new GetObjectRequest(bucketName, objectName);
            getObjectRequest.setRange(1000, 2000);
            getObjectRequest.addHeader("x-oss-range-behavior", "standard");
            OSSObject ossObject2 = ossClient.getObject(getObjectRequest);
            ossObject2.close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

相關文檔

關於範圍下載的API介面說明,請參見GetObject