

 **此頁面僅適用於使用 Vaults 和 2012 年原始 REST API 的 Amazon Glacier 服務的現有客戶。**

如果您要尋找封存儲存解決方案，建議您在 Amazon Glacier Instant Retrieval、S3 Glacier Flexible Retrieval 和 S3 Glacier Deep Archive 中使用 Amazon Glacier 儲存類別。 Amazon S3 若要進一步了解這些儲存選項，請參閱 [Amazon Glacier 儲存類別](https://aws.amazon.com/s3/storage-classes/glacier/)。

Amazon Glacier （原始獨立保存庫型服務） 不再接受新客戶。Amazon Glacier 是一項獨立服務，具有自己的 APIs，可將資料存放在保存庫中，並與 Amazon S3 和 Amazon S3 Glacier 儲存類別不同。您現有的資料將在 Amazon Glacier 中無限期保持安全且可存取。不需要遷移。對於低成本、長期的封存儲存， AWS 建議使用 [Amazon S3 Glacier 儲存類別](https://aws.amazon.com/s3/storage-classes/glacier/)，透過 S3 儲存貯體型 APIs、完整 AWS 區域 可用性、降低成本 AWS 和服務整合，提供卓越的客戶體驗。如果您想要增強功能，請考慮使用我們的解決方案指南，將資料從 Amazon S3 Glacier 保存庫傳輸至 Amazon S3 Glacier 儲存類別，以遷移至 Amazon S3 Glacier 儲存類別。 [AWS Amazon Glacier Amazon S3 ](https://aws.amazon.com/solutions/guidance/data-transfer-from-amazon-s3-glacier-vaults-to-amazon-s3/)

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 步驟 3：將封存上傳至 Amazon Glacier 中的保存庫
<a name="getting-started-upload-archive"></a>

在此步驟中，將範例封存上傳到在前面步驟中所建立的保存庫中 (請參閱 [步驟 2：在 Amazon Glacier 中建立保存庫](getting-started-create-vault.md))。根據所使用的開發平台，選擇本節結尾的其中一個連結。

**重要**  
任何封存作業 (例如上傳、下載或刪除) 都要求您使用 AWS Command Line Interface (CLI) 或撰寫程式碼。沒有主控台支援封存操作。例如，若要上傳資料，例如相片、影片和其他文件，您必須使用 AWS CLI 或編寫程式碼來提出請求，方法是直接使用 REST API 或使用 AWS SDKs。  
若要安裝 AWS CLI，請參閱 [AWS Command Line Interface](https://aws.amazon.com/cli/)。如需搭配 使用 Amazon Glacier 的詳細資訊 AWS CLI，請參閱 [AWS CLI Amazon Glacier 的參考](https://docs.aws.amazon.com/cli/latest/reference/glacier/index.html)。如需使用 AWS CLI 將封存上傳至 Amazon Glacier 的範例，請參閱[搭配使用 Amazon Glacier 與 AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-using-glacier.html)。

封存是存放在保存庫中的任何物件 (如相片、影片或文件)。存檔是 Amazon Glacier 中儲存體的基本單位。您可以在單一請求中上傳封存。對於大型封存，Amazon Glacier 提供分段上傳 API 操作，可讓您分段上傳封存。

在此入門部分，您在單一請求中上傳範例封存。本練習中，指定一個較小的檔案。對於較大的檔案，分段上傳是合適的。如需詳細資訊，請參閱[上傳分段中的大型封存 (分段上傳)](uploading-archive-mpu.md)。

**Topics**
+ [

# 使用 將封存上傳至 Amazon Glacier 中的保存庫 適用於 Java 的 AWS SDK
](getting-started-upload-archive-java.md)
+ [

# 使用 將封存上傳至 Amazon Glacier 中的保存庫 適用於 .NET 的 AWS SDK
](getting-started-upload-archive-dotnet.md)

# 使用 將封存上傳至 Amazon Glacier 中的保存庫 適用於 Java 的 AWS SDK
<a name="getting-started-upload-archive-java"></a>

下列 Java 程式碼範例使用 的高階 API， 適用於 Java 的 AWS SDK 將範例封存上傳至保存庫。在程式碼範例中，請注意下列事項：
+ 範例會建立 `AmazonGlacierClient` 類別的執行個體。
+ 此範例使用 適用於 Java 的 AWS SDK高階 API 的 `ArchiveTransferManager` 類別的 `upload` API 作業。
+ 此範例使用美國西部 (奧勒岡) 區域 (`us-west-2`)。

如需執行此範例的逐步說明，請參閱 [使用 Eclipse 執行 Amazon Glacier 的 Java 範例](using-aws-sdk-for-java.md#setting-up-and-testing-sdk-java)。您必須如所示，使用要更新之封存檔的名稱更新程式碼。

**注意**  
Amazon Glacier 會保留保存庫中所有封存的庫存。當您上傳下列範例中的存檔時，它將不會顯示管理主控台的文件庫中，直到文件庫清查已更新。此更新通常一天執行一次。

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)中設定和執行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.UploadArchiveRequest;
import software.amazon.awssdk.services.glacier.model.UploadArchiveResponse;
import software.amazon.awssdk.services.glacier.model.GlacierException;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class UploadArchive {

    static final int ONE_MB = 1024 * 1024;

    public static void main(String[] args) {
        final String usage = """

                Usage:   <strPath> <vaultName>\s

                Where:
                   strPath - The path to the archive to upload (for example, C:\\AWS\\test.pdf).
                   vaultName - The name of the vault.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String strPath = args[0];
        String vaultName = args[1];
        File myFile = new File(strPath);
        Path path = Paths.get(strPath);
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String archiveId = uploadContent(glacier, path, vaultName, myFile);
        System.out.println("The ID of the archived item is " + archiveId);
        glacier.close();
    }

    public static String uploadContent(GlacierClient glacier, Path path, String vaultName, File myFile) {
        // Get an SHA-256 tree hash value.
        String checkVal = computeSHA256(myFile);
        try {
            UploadArchiveRequest uploadRequest = UploadArchiveRequest.builder()
                    .vaultName(vaultName)
                    .checksum(checkVal)
                    .build();

            UploadArchiveResponse res = glacier.uploadArchive(uploadRequest, path);
            return res.archiveId();

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    private static String computeSHA256(File inputFile) {
        try {
            byte[] treeHash = computeSHA256TreeHash(inputFile);
            System.out.printf("SHA-256 tree hash = %s\n", toHex(treeHash));
            return toHex(treeHash);

        } catch (IOException ioe) {
            System.err.format("Exception when reading from file %s: %s", inputFile, ioe.getMessage());
            System.exit(-1);

        } catch (NoSuchAlgorithmException nsae) {
            System.err.format("Cannot locate MessageDigest algorithm for SHA-256: %s", nsae.getMessage());
            System.exit(-1);
        }
        return "";
    }

    public static byte[] computeSHA256TreeHash(File inputFile) throws IOException,
            NoSuchAlgorithmException {

        byte[][] chunkSHA256Hashes = getChunkSHA256Hashes(inputFile);
        return computeSHA256TreeHash(chunkSHA256Hashes);
    }

    /**
     * Computes an SHA256 checksum for each 1 MB chunk of the input file. This
     * includes the checksum for the last chunk, even if it's smaller than 1 MB.
     */
    public static byte[][] getChunkSHA256Hashes(File file) throws IOException,
            NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        long numChunks = file.length() / ONE_MB;
        if (file.length() % ONE_MB > 0) {
            numChunks++;
        }

        if (numChunks == 0) {
            return new byte[][] { md.digest() };
        }

        byte[][] chunkSHA256Hashes = new byte[(int) numChunks][];
        FileInputStream fileStream = null;

        try {
            fileStream = new FileInputStream(file);
            byte[] buff = new byte[ONE_MB];

            int bytesRead;
            int idx = 0;

            while ((bytesRead = fileStream.read(buff, 0, ONE_MB)) > 0) {
                md.reset();
                md.update(buff, 0, bytesRead);
                chunkSHA256Hashes[idx++] = md.digest();
            }

            return chunkSHA256Hashes;

        } finally {
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (IOException ioe) {
                    System.err.printf("Exception while closing %s.\n %s", file.getName(),
                            ioe.getMessage());
                }
            }
        }
    }

    /**
     * Computes the SHA-256 tree hash for the passed array of 1 MB chunk
     * checksums.
     */
    public static byte[] computeSHA256TreeHash(byte[][] chunkSHA256Hashes)
            throws NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[][] prevLvlHashes = chunkSHA256Hashes;
        while (prevLvlHashes.length > 1) {
            int len = prevLvlHashes.length / 2;
            if (prevLvlHashes.length % 2 != 0) {
                len++;
            }

            byte[][] currLvlHashes = new byte[len][];
            int j = 0;
            for (int i = 0; i < prevLvlHashes.length; i = i + 2, j++) {

                // If there are at least two elements remaining.
                if (prevLvlHashes.length - i > 1) {

                    // Calculate a digest of the concatenated nodes.
                    md.reset();
                    md.update(prevLvlHashes[i]);
                    md.update(prevLvlHashes[i + 1]);
                    currLvlHashes[j] = md.digest();

                } else { // Take care of the remaining odd chunk
                    currLvlHashes[j] = prevLvlHashes[i];
                }
            }

            prevLvlHashes = currLvlHashes;
        }

        return prevLvlHashes[0];
    }

    /**
     * Returns the hexadecimal representation of the input byte array
     */
    public static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (byte datum : data) {
            String hex = Integer.toHexString(datum & 0xFF);

            if (hex.length() == 1) {
                // Append leading zero.
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString().toLowerCase();
    }
}
```
+  如需 API 的詳細資訊，請參閱《*AWS SDK for Java 2.x API 參考*》的 [UploadArchive](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/UploadArchive)。

# 使用 將封存上傳至 Amazon Glacier 中的保存庫 適用於 .NET 的 AWS SDK
<a name="getting-started-upload-archive-dotnet"></a>

下列 C\$1 程式碼範例使用 的高階 API， 適用於 .NET 的 AWS SDK 將範例封存上傳至保存庫。在程式碼範例中，請注意下列事項：

 
+ 此範例會為指定的 Amazon Glacier 區域端點建立 `ArchiveTransferManager`類別的執行個體。
+ 此程式碼範例使用美國西部 (奧勒岡) 區域 (`us-west-2`)。
+ 本範例使用 `ArchiveTransferManager` 類別的 `Upload` API 作業以上傳封存。對於小型封存，此操作會將封存直接上傳至 Amazon Glacier。對於較大的封存，如果在將資料串流至 Amazon Glacier 時遇到任何錯誤，此操作會使用 Amazon Glacier 中的分段上傳 API 操作將上傳分割為多個部分，以獲得更好的錯誤復原。

如需如何執行下列範例的逐步說明，請參閱 [執行程式碼範例](using-aws-sdk-for-dot-net.md#setting-up-and-testing-sdk-dotnet)。您必須更新程式碼，如所示的保存庫名稱和要上傳的封存檔案的名稱。

**注意**  
Amazon Glacier 會保留保存庫中所有封存的庫存。當您上傳下列範例中的封存時，直到保存庫庫存更新前，封存都不會顯示在管理主控台的保存庫中。此更新通常一天執行一次。

**Example — 使用 的高階 API 上傳封存 適用於 .NET 的 AWS SDK**  <a name="GS_ExampleUploadArchiveDotNet"></a>

```
using System;
using Amazon.Glacier;
using Amazon.Glacier.Transfer;
using Amazon.Runtime;

namespace glacier.amazon.com.rproxy.govskope.ca.docsamples
{
    class ArchiveUploadHighLevel_GettingStarted
    {
        static string vaultName = "examplevault";
        static string archiveToUpload = "*** Provide file name (with full path) to upload ***";

        public static void Main(string[] args)
        {
            try
            {
                var manager = new ArchiveTransferManager(Amazon.RegionEndpoint.USWest2);
                // Upload an archive.
                string archiveId = manager.Upload(vaultName, "getting started archive test", archiveToUpload).ArchiveId;
                Console.WriteLine("Copy and save the following Archive ID for the next step."); 
                Console.WriteLine("Archive ID: {0}", archiveId);
                Console.WriteLine("To continue, press Enter");
                Console.ReadKey();
            }
            catch (AmazonGlacierException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
            Console.WriteLine("To continue, press Enter");
            Console.ReadKey();
        }
    }
}
```