Tải tệp javascript xuống đĩa cục bộ

Trang này chỉ cho bạn cách tải các đối tượng từ bộ chứa của bạn trong Lưu trữ đám mây xuống bộ lưu trữ liên tục. Bạn cũng có thể tải các đối tượng vào bộ nhớ

Ghi chú. Nếu bạn sử dụng các khóa mã hóa do khách hàng cung cấp với các đối tượng của mình, hãy xem hướng dẫn tải xuống

quyền cần thiết

Bảng điều khiển

Để hoàn thành hướng dẫn này bằng bảng điều khiển Google Cloud, bạn phải có quyền IAM phù hợp. Nếu nhóm bạn muốn tải xuống tồn tại trong một dự án mà bạn không tạo, thì bạn có thể cần chủ sở hữu dự án cấp cho bạn một vai trò có chứa các quyền cần thiết

Để biết danh sách các quyền cần thiết cho các hành động cụ thể, hãy xem quyền IAM cho bảng điều khiển Google Cloud

Để biết danh sách các vai trò có liên quan, hãy xem vai trò Lưu trữ đám mây. Ngoài ra, bạn có thể tạo một vai trò tùy chỉnh có các quyền hạn chế, cụ thể

Dòng lệnh

Để hoàn thành hướng dẫn này bằng tiện ích dòng lệnh, bạn phải có quyền IAM phù hợp. Nếu nhóm bạn muốn tải xuống tồn tại trong một dự án mà bạn không tạo, thì bạn có thể cần chủ sở hữu dự án cấp cho bạn một vai trò có chứa các quyền cần thiết

Để biết danh sách các quyền cần thiết cho các hành động cụ thể, hãy xem quyền IAM cho các lệnh gsutil

Để biết danh sách các vai trò có liên quan, hãy xem vai trò Lưu trữ đám mây. Ngoài ra, bạn có thể tạo một vai trò tùy chỉnh có các quyền hạn chế, cụ thể

thư viện máy khách

Để hoàn thành hướng dẫn này bằng thư viện máy khách Cloud Storage, bạn phải có quyền IAM phù hợp. Nếu nhóm bạn muốn tải xuống tồn tại trong một dự án mà bạn không tạo, thì bạn có thể cần chủ sở hữu dự án cấp cho bạn một vai trò có chứa các quyền cần thiết

Trừ khi có ghi chú khác, các yêu cầu thư viện máy khách được thực hiện thông qua API JSON và yêu cầu các quyền như được liệt kê trong quyền IAM cho các phương thức JSON. Để xem phương thức API JSON nào được gọi khi bạn thực hiện yêu cầu bằng thư viện máy khách,

Để biết danh sách các vai trò IAM có liên quan, hãy xem vai trò Lưu trữ đám mây. Ngoài ra, bạn có thể tạo một vai trò tùy chỉnh có các quyền hạn chế, cụ thể

API REST

API JSON

Để hoàn thành hướng dẫn này bằng API JSON, bạn phải có quyền IAM phù hợp. Nếu nhóm bạn muốn tải xuống tồn tại trong một dự án mà bạn không tạo, thì bạn có thể cần chủ sở hữu dự án cấp cho bạn một vai trò có chứa các quyền cần thiết

Để biết danh sách các quyền cần thiết cho các hành động cụ thể, hãy xem quyền IAM cho các phương thức JSON

Để biết danh sách các vai trò có liên quan, hãy xem vai trò Lưu trữ đám mây. Ngoài ra, bạn có thể tạo một vai trò tùy chỉnh có các quyền hạn chế, cụ thể

Tải xuống một đối tượng từ một thùng

Hoàn thành các hướng dẫn sau để tải xuống một đối tượng từ bộ chứa

Bảng điều khiển

  1. Trong bảng điều khiển Google Cloud, hãy truy cập trang Nhóm lưu trữ đám mây

    Chuyển đến Nhóm

  2. Trong danh sách các nhóm, nhấp vào tên của nhóm chứa đối tượng bạn muốn tải xuống

    Trang chi tiết bộ chứa mở ra với tab Đối tượng được chọn

  3. Điều hướng đến đối tượng, có thể nằm trong một thư mục

  4. Nhấp vào biểu tượng Tải xuống được liên kết với đối tượng

    Cài đặt trình duyệt của bạn kiểm soát vị trí tải xuống cho đối tượng

Ghi chú. Đối với một số loại đối tượng, việc chọn Tải xuống sẽ mở đối tượng trong trình duyệt. Để tải các đối tượng này xuống máy tính cục bộ của bạn, nhấp chuột phải vào Tải xuống và chọn Lưu liên kết dưới dạng.

Để tìm hiểu cách nhận thông tin lỗi chi tiết về các hoạt động của Cloud Storage không thành công trong bảng điều khiển Google Cloud, hãy xem

Dòng lệnh

gcloud

Sử dụng lệnh

gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
4

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION

Ở đâu

  • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    5 là tên của nhóm chứa đối tượng bạn đang tải xuống. Ví dụ,
    gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    6

  • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    7 là tên của đối tượng bạn đang tải xuống. Ví dụ,
    gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    8

  • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    9 là đường dẫn cục bộ nơi bạn đang lưu đối tượng của mình. Ví dụ,
    Operation completed over 1 objects/58.8 KiB.
    0

Nếu thành công, phản hồi sẽ giống như ví dụ sau

________số 8_______

Nếu quá trình tải xuống của bạn bị gián đoạn trước khi hoàn thành, hãy chạy cùng một lệnh

Operation completed over 1 objects/58.8 KiB.
1 để tiếp tục tải xuống từ nơi dừng lại

gsutil

Sử dụng lệnh

Operation completed over 1 objects/58.8 KiB.
2

gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION

Ở đâu

  • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    5 là tên của nhóm chứa đối tượng bạn đang tải xuống. Ví dụ,
    gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    6

  • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    7 là tên của đối tượng bạn đang tải xuống. Ví dụ,
    gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    8

  • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    9 là đường dẫn cục bộ nơi bạn đang lưu đối tượng của mình. Ví dụ,
    Operation completed over 1 objects/58.8 KiB.
    0

Nếu thành công, phản hồi sẽ giống như ví dụ sau

Operation completed over 1 objects/58.8 KiB.

Nếu quá trình tải xuống của bạn bị gián đoạn trước khi hoàn thành, hãy chạy cùng một lệnh

Operation completed over 1 objects/58.8 KiB.
1 để tiếp tục tải xuống từ nơi dừng lại

thư viện máy khách

C++

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API Bộ nhớ đám mây C++ .

Xem trên GitHub

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);

  int count = 0;
  std::string line;
  while (std::getline(stream, line, '\n')) {
    ++count;
  }

  std::cout << "The object has " << count << " lines\n";
}

C#

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API Lưu trữ đám mây C# .

Xem trên GitHub


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class DownloadFileSample
{
    public void DownloadFile(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string localPath = "my-local-path/my-file-name")
    {
        var storage = StorageClient.Create();
        using var outputFile = File.OpenWrite(localPath);
        storage.DownloadObject(bucketName, objectName, outputFile);
        Console.WriteLine($"Downloaded {objectName} to {localPath}.");
    }
}

Đi

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API Bộ nhớ đám mây Go .

Xem trên GitHub

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %v", err)
	}

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	defer rc.Close()

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %v", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}

Java

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API lưu trữ đám mây Java .

Xem trên GitHub


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.file.Paths;

public class DownloadObject {
  public static void downloadObject(
      String projectId, String bucketName, String objectName, String destFilePath) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to which the file should be downloaded
    // String destFilePath = "/local/path/to/file.txt";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Blob blob = storage.get(BlobId.of(bucketName, objectName));
    blob.downloadTo(Paths.get(destFilePath));

    System.out.println(
        "Downloaded object "
            + objectName
            + " from bucket name "
            + bucketName
            + " to "
            + destFilePath);
  }
}

Nút. js

Để biết thêm thông tin, hãy xem Bộ nhớ đám mây Nút. js Tài liệu tham khảo API.

Xem trên GitHub

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadFile() {
  const options = {
    destination: destFileName,
  };

  // Downloads the file
  await storage.bucket(bucketName).file(fileName).download(options);

  console.log(
    `gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
  );
}

downloadFile().catch(console.error);

PHP

Để biết thêm thông tin, hãy xem

Xem trên GitHub

use Google\Cloud\Storage\StorageClient;

/**
 * Download an object from Cloud Storage and save it as a local file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $destination The local destination to save the object.
 *        (e.g. '/path/to/your/file')
 */
function download_object(string $bucketName, string $objectName, string $destination): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf(
        'Downloaded gs://%s/%s to %s' . PHP_EOL,
        $bucketName,
        $objectName,
        basename($destination)
    );
}

con trăn

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API lưu trữ đám mây Python .

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
0

hồng ngọc

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API của Bộ lưu trữ đám mây Ruby .

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
1

API REST

API JSON

  1. Nhận mã thông báo truy cập ủy quyền từ OAuth 2. 0 sân chơi. Định cấu hình sân chơi để sử dụng thông tin đăng nhập OAuth của riêng bạn. Để biết hướng dẫn, hãy xem
  2. Sử dụng

    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    0 để gọi API JSON với yêu cầu đối tượng
    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    1

    Completed files 1/1 | 164.3kiB/164.3kiB
    2

    Ở đâu

    • namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      2 là mã thông báo truy cập bạn đã tạo ở Bước 1
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      9 là đường dẫn đến vị trí bạn muốn lưu đối tượng của mình. Ví dụ,
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      4
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      5 là tên của nhóm chứa đối tượng bạn đang tải xuống. Ví dụ,
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      6
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      7 là tên được mã hóa URL của đối tượng bạn đang tải xuống. Ví dụ:
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      8, URL được mã hóa thành
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      9

API XML

  1. Nhận mã thông báo truy cập ủy quyền từ OAuth 2. 0 sân chơi. Định cấu hình sân chơi để sử dụng thông tin đăng nhập OAuth của riêng bạn. Để biết hướng dẫn, hãy xem
  2. Sử dụng

    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    0 để gọi API XML với một yêu cầu đối tượng
    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    1

    Completed files 1/1 | 164.3kiB/164.3kiB
    3

    Ở đâu

    • namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      2 là mã thông báo truy cập bạn đã tạo ở Bước 1
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      9 là đường dẫn đến vị trí bạn muốn lưu đối tượng của mình. Ví dụ,
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      4
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      5 là tên của nhóm chứa đối tượng bạn đang tải xuống. Ví dụ,
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      6
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      7 là tên được mã hóa URL của đối tượng bạn đang tải xuống. Ví dụ:
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      8, URL được mã hóa thành
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      9

Để dễ dàng tải xuống tất cả các đối tượng trong nhóm hoặc thư mục con, hãy sử dụng lệnh

Operation completed over 1 objects/58.8 KiB.
2 hoặc
gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
4

Tải xuống một phần của đối tượng

Nếu quá trình tải xuống của bạn bị gián đoạn, bạn có thể tiếp tục từ nơi bạn đã dừng lại bằng cách chỉ yêu cầu phần đối tượng còn lại. Hoàn thành các hướng dẫn sau để tải xuống một phần của đối tượng

Bảng điều khiển

Bảng điều khiển Google Cloud không hỗ trợ tải xuống các phần của đối tượng. Thay vào đó, hãy sử dụng gcloud CLI

Dòng lệnh

gcloud

gcloud tự động cố gắng tiếp tục tải xuống bị gián đoạn, trừ khi thực hiện tải xuống trực tuyến. Nếu quá trình tải xuống của bạn bị gián đoạn, tệp tạm thời được tải xuống một phần sẽ hiển thị trong hệ thống phân cấp đích. Chạy cùng một lệnh

Operation completed over 1 objects/58.8 KiB.
1 để tiếp tục tải xuống ở nơi nó đã dừng lại

Khi quá trình tải xuống hoàn tất, tệp tạm thời sẽ bị xóa và thay thế bằng nội dung đã tải xuống. Các tệp tạm thời được lưu trữ ở một vị trí có thể định cấu hình, theo mặc định, vị trí này nằm trong thư mục chính của người dùng bên dưới

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %v", err)
	}

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	defer rc.Close()

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %v", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}
3. Bạn có thể thay đổi hoặc xem vị trí mà các tệp tạm thời được lưu trữ bằng cách chạy
import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %v", err)
	}

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	defer rc.Close()

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %v", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}
4

gsutil

gsutil tự động cố gắng tiếp tục tải xuống bị gián đoạn, trừ khi thực hiện tải xuống trực tuyến. Nếu quá trình tải xuống của bạn bị gián đoạn, tệp tạm thời được tải xuống một phần sẽ hiển thị trong thư mục đích. Chạy cùng một lệnh

Operation completed over 1 objects/58.8 KiB.
1 để tiếp tục tải xuống ở nơi nó đã dừng lại

Khi quá trình tải xuống hoàn tất, tệp tạm thời sẽ bị xóa và thay thế bằng nội dung đã tải xuống. Chuyển giao có thể tiếp tục lưu trữ thông tin trạng thái trong các tệp theo

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %v", err)
	}

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	defer rc.Close()

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %v", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}
6, được đặt tên theo đối tượng hoặc tệp đích

thư viện máy khách

C++

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API Bộ nhớ đám mây C++ .

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
4

C#

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API Lưu trữ đám mây C# .

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
5

Đi

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API Bộ nhớ đám mây Go .

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
6

Java

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API lưu trữ đám mây Java .

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
7

Nút. js

Để biết thêm thông tin, hãy xem Bộ nhớ đám mây Nút. js Tài liệu tham khảo API.

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
8

PHP

Để biết thêm thông tin, hãy xem

Xem trên GitHub

Completed files 1/1 | 164.3kiB/164.3kiB
9

con trăn

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API lưu trữ đám mây Python .

Xem trên GitHub

gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
0

hồng ngọc

Để biết thêm thông tin, hãy xem tài liệu tham khảo về API của Bộ lưu trữ đám mây Ruby .

Xem trên GitHub

gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
1

API REST

API JSON

Sử dụng trong yêu cầu của bạn để tải xuống một phần của đối tượng

  1. Nhận mã thông báo truy cập ủy quyền từ OAuth 2. 0 sân chơi. Định cấu hình sân chơi để sử dụng thông tin đăng nhập OAuth của riêng bạn. Để biết hướng dẫn, hãy xem
  2. Sử dụng

    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    0 để gọi API JSON với yêu cầu đối tượng
    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    1

    gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    2

    Ở đâu

    • namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      2 là mã thông báo truy cập bạn đã tạo ở Bước 1
    • 
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      1 là byte đầu tiên trong phạm vi byte bạn muốn tải xuống. Ví dụ,
      
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      2
    • 
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      3 là byte cuối cùng trong phạm vi byte bạn muốn tải xuống. Ví dụ,
      
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      4
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      9 là đường dẫn đến vị trí bạn muốn lưu đối tượng của mình. Ví dụ,
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      4
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      5 là tên của nhóm chứa đối tượng bạn đang tải xuống. Ví dụ,
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      6
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      7 là tên được mã hóa URL của đối tượng bạn đang tải xuống. Ví dụ:
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      8, URL được mã hóa thành
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      9
Ghi chú. Nếu quá trình chuyển mã đối tượng diễn ra, tiêu đề
import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %v", err)
	}

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	defer rc.Close()

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %v", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}
7 sẽ bị bỏ qua một cách im lặng và thay vào đó, phản hồi sẽ phục vụ toàn bộ đối tượng được yêu cầu.

API XML

Sử dụng trong yêu cầu của bạn để tải xuống một phần của đối tượng

  1. Nhận mã thông báo truy cập ủy quyền từ OAuth 2. 0 sân chơi. Định cấu hình sân chơi để sử dụng thông tin đăng nhập OAuth của riêng bạn. Để biết hướng dẫn, hãy xem
  2. Sử dụng

    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    0 để gọi API XML với một yêu cầu đối tượng
    namespace gcs = ::google::cloud::storage;
    [](gcs::Client client, std::string const& bucket_name,
       std::string const& object_name) {
      gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
    
      int count = 0;
      std::string line;
      while (std::getline(stream, line, '\n')) {
        ++count;
      }
    
      std::cout << "The object has " << count << " lines\n";
    }
    1

    gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
    3

    Ở đâu

    • namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      2 là mã thông báo truy cập bạn đã tạo ở Bước 1
    • 
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      1 là byte đầu tiên trong phạm vi byte bạn muốn tải xuống. Ví dụ,
      
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      2
    • 
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      3 là byte cuối cùng trong phạm vi byte bạn muốn tải xuống. Ví dụ,
      
      import com.google.cloud.storage.Blob;
      import com.google.cloud.storage.BlobId;
      import com.google.cloud.storage.Storage;
      import com.google.cloud.storage.StorageOptions;
      import java.nio.file.Paths;
      
      public class DownloadObject {
        public static void downloadObject(
            String projectId, String bucketName, String objectName, String destFilePath) {
          // The ID of your GCP project
          // String projectId = "your-project-id";
      
          // The ID of your GCS bucket
          // String bucketName = "your-unique-bucket-name";
      
          // The ID of your GCS object
          // String objectName = "your-object-name";
      
          // The path to which the file should be downloaded
          // String destFilePath = "/local/path/to/file.txt";
      
          Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
      
          Blob blob = storage.get(BlobId.of(bucketName, objectName));
          blob.downloadTo(Paths.get(destFilePath));
      
          System.out.println(
              "Downloaded object "
                  + objectName
                  + " from bucket name "
                  + bucketName
                  + " to "
                  + destFilePath);
        }
      }
      4
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      9 là đường dẫn đến vị trí bạn muốn lưu đối tượng của mình. Ví dụ,
      use Google\Cloud\Storage\StorageClient;
      
      /**
       * Download an object from Cloud Storage and save it as a local file.
       *
       * @param string $bucketName The name of your Cloud Storage bucket.
       *        (e.g. 'my-bucket')
       * @param string $objectName The name of your Cloud Storage object.
       *        (e.g. 'my-object')
       * @param string $destination The local destination to save the object.
       *        (e.g. '/path/to/your/file')
       */
      function download_object(string $bucketName, string $objectName, string $destination): void
      {
          $storage = new StorageClient();
          $bucket = $storage->bucket($bucketName);
          $object = $bucket->object($objectName);
          $object->downloadToFile($destination);
          printf(
              'Downloaded gs://%s/%s to %s' . PHP_EOL,
              $bucketName,
              $objectName,
              basename($destination)
          );
      }
      2
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      5 là tên của nhóm chứa đối tượng bạn đang tải xuống. Ví dụ,
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      6
    • gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      7 là tên được mã hóa URL của đối tượng bạn đang tải xuống. Ví dụ:
      gsutil cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION
      8, URL được mã hóa thành
      namespace gcs = ::google::cloud::storage;
      [](gcs::Client client, std::string const& bucket_name,
         std::string const& object_name) {
        gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
      
        int count = 0;
        std::string line;
        while (std::getline(stream, line, '\n')) {
          ++count;
        }
      
        std::cout << "The object has " << count << " lines\n";
      }
      9
Ghi chú. Nếu quá trình chuyển mã đối tượng diễn ra, tiêu đề
import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadFile downloads an object to a file.
func downloadFile(w io.Writer, bucket, object string, destFileName string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// destFileName := "file.txt"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	f, err := os.Create(destFileName)
	if err != nil {
		return fmt.Errorf("os.Create: %v", err)
	}

	rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	defer rc.Close()

	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}

	if err = f.Close(); err != nil {
		return fmt.Errorf("f.Close: %v", err)
	}

	fmt.Fprintf(w, "Blob %v downloaded to local file %v\n", object, destFileName)

	return nil

}
7 sẽ bị bỏ qua một cách im lặng và thay vào đó, phản hồi sẽ phục vụ toàn bộ đối tượng được yêu cầu.

Cái gì tiếp theo

  • Đọc tổng quan khái niệm về tải lên và tải xuống, bao gồm các chiến lược tải xuống nâng cao
  • Truyền dữ liệu từ nhà cung cấp đám mây hoặc các nguồn trực tuyến khác, chẳng hạn như danh sách URL
  • .
  • Tìm hiểu cách bạn có thể tính phí truy cập Cloud Storage cho người yêu cầu
  • Tìm hiểu cách Cloud Storage có thể phục vụ các tệp được nén ở trạng thái không nén

Hãy thử nó cho chính mình

Nếu bạn mới sử dụng Google Cloud, hãy tạo một tài khoản để đánh giá hiệu suất của Cloud Storage trong các tình huống thực tế. Khách hàng mới cũng nhận được 300 đô la tín dụng miễn phí để chạy, thử nghiệm và triển khai khối lượng công việc

Làm cách nào để tải xuống tệp cục bộ bằng JavaScript?

Vậy các bước tải file sẽ là. .
Sử dụng API tìm nạp để tải xuống tệp tập lệnh
Chuyển đổi dữ liệu thành loại blob
Chuyển đổi đối tượng blob thành chuỗi bằng cách sử dụng URL. tạoObjectURL()

JavaScript có thể tải xuống tệp không?

JavaScript cung cấp thuộc tính href để tải tệp xuống . Thuộc tính được hỗ trợ bởi HTML 5. Sử dụng thuộc tính này, người dùng có thể sử dụng liên kết cũng như nút tải xuống tệp theo nhu cầu của mình. Hai ví dụ được giải thích chi tiết để tải xuống các tệp văn bản cũng như hình ảnh trong JavaScript.

Làm cách nào để lấy đường dẫn tệp đã tải xuống trong JavaScript?

Điều đó là không thể. Trình duyệt thuần túy- JavaScript không thể lấy thông tin về hệ thống tệp của người dùng . Đường dẫn tải xuống mặc định cũng có thể chứa thông tin hợp lý, điều này rất rủi ro. Hãy tưởng tượng rằng một người lưu trữ các bản tải xuống của mình tại C. \Tên công ty\Tên thật\Số điện thoại\Địa chỉ\.

Làm cách nào để lưu tệp bằng JavaScript?