Tải file lên bằng Cloud Storage trên nền tảng Apple

Cloud Storage cho Firebase cho phép bạn tải tệp lên nhóm Cloud Storage do Firebase cung cấp và quản lý một cách nhanh chóng và dễ dàng.

Tạo một tài liệu tham khảo

Để tải tệp lên, trước tiên hãy tạo tham chiếu Cloud Storage tới vị trí trong Cloud Storage mà bạn muốn tải tệp lên.

Bạn có thể tạo một tham chiếu bằng cách thêm các đường dẫn con vào thư mục gốc của nhóm Cloud Storage:

Nhanh

// Create a root reference
let storageRef = storage.reference()

// Create a reference to "mountains.jpg"
let mountainsRef = storageRef.child("mountains.jpg")

// Create a reference to 'images/mountains.jpg'
let mountainImagesRef = storageRef.child("images/mountains.jpg")

// While the file names are the same, the references point to different files
mountainsRef.name == mountainImagesRef.name            // true
mountainsRef.fullPath == mountainImagesRef.fullPath    // false
    

Mục tiêu-C

// Create a root reference
FIRStorageReference *storageRef = [storage reference];

// Create a reference to "mountains.jpg"
FIRStorageReference *mountainsRef = [storageRef child:@"mountains.jpg"];

// Create a reference to 'images/mountains.jpg'
FIRStorageReference *mountainImagesRef = [storageRef child:@"images/mountains.jpg"];

// While the file names are the same, the references point to different files
[mountainsRef.name isEqualToString:mountainImagesRef.name];         // true
[mountainsRef.fullPath isEqualToString:mountainImagesRef.fullPath]; // false
  

Bạn không thể tải lên dữ liệu có tham chiếu đến thư mục gốc của bộ chứa Cloud Storage. Tham chiếu của bạn phải trỏ đến URL con.

Tải tập tin lên

Sau khi đã có tài liệu tham khảo, bạn có thể upload file lên Cloud Storage theo 2 cách:

  1. Tải lên từ dữ liệu trong bộ nhớ
  2. Tải lên từ URL đại diện cho một tệp trên thiết bị

Tải lên từ dữ liệu trong bộ nhớ

Phương thức putData:metadata:completion: là cách đơn giản nhất để tải tệp lên Cloud Storage. putData:metadata:completion: lấy một đối tượng NSData và trả về một FIRStorageUploadTask mà bạn có thể sử dụng để quản lý quá trình tải lên của mình và theo dõi trạng thái của nó.

Nhanh

// Data in memory
let data = Data()

// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")

// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(data, metadata: nil) { (metadata, error) in
  guard let metadata = metadata else {
    // Uh-oh, an error occurred!
    return
  }
  // Metadata contains file metadata such as size, content-type.
  let size = metadata.size
  // You can also access to download URL after upload.
  riversRef.downloadURL { (url, error) in
    guard let downloadURL = url else {
      // Uh-oh, an error occurred!
      return
    }
  }
}
    

Mục tiêu-C

// Data in memory
NSData *data = [NSData dataWithContentsOfFile:@"rivers.jpg"];

// Create a reference to the file you want to upload
FIRStorageReference *riversRef = [storageRef child:@"images/rivers.jpg"];

// Upload the file to the path "images/rivers.jpg"
FIRStorageUploadTask *uploadTask = [riversRef putData:data
                                             metadata:nil
                                           completion:^(FIRStorageMetadata *metadata,
                                                        NSError *error) {
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Metadata contains file metadata such as size, content-type, and download URL.
    int size = metadata.size;
    // You can also access to download URL after upload.
    [riversRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
      if (error != nil) {
        // Uh-oh, an error occurred!
      } else {
        NSURL *downloadURL = URL;
      }
    }];
  }
}];
  

Tải lên từ một tập tin cục bộ

Bạn có thể tải các tệp cục bộ lên thiết bị, chẳng hạn như ảnh và video từ máy ảnh, bằng phương thức putFile:metadata:completion: putFile:metadata:completion: lấy NSURL và trả về FIRStorageUploadTask mà bạn có thể sử dụng để quản lý nội dung tải lên của mình và theo dõi trạng thái của nó.

Nhanh

// File located on disk
let localFile = URL(string: "path/to/image")!

// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")

// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putFile(from: localFile, metadata: nil) { metadata, error in
  guard let metadata = metadata else {
    // Uh-oh, an error occurred!
    return
  }
  // Metadata contains file metadata such as size, content-type.
  let size = metadata.size
  // You can also access to download URL after upload.
  riversRef.downloadURL { (url, error) in
    guard let downloadURL = url else {
      // Uh-oh, an error occurred!
      return
    }
  }
}
    

Mục tiêu-C

// File located on disk
NSURL *localFile = [NSURL URLWithString:@"path/to/image"];

// Create a reference to the file you want to upload
FIRStorageReference *riversRef = [storageRef child:@"images/rivers.jpg"];

// Upload the file to the path "images/rivers.jpg"
FIRStorageUploadTask *uploadTask = [riversRef putFile:localFile metadata:nil completion:^(FIRStorageMetadata *metadata, NSError *error) {
  if (error != nil) {
    // Uh-oh, an error occurred!
  } else {
    // Metadata contains file metadata such as size, content-type, and download URL.
    int size = metadata.size;
    // You can also access to download URL after upload.
    [riversRef downloadURLWithCompletion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
      if (error != nil) {
        // Uh-oh, an error occurred!
      } else {
        NSURL *downloadURL = URL;
      }
    }];
  }
}];
  

Nếu muốn chủ động quản lý quá trình tải lên của mình, bạn có thể sử dụng các phương thức putData: hoặc putFile: và quan sát tác vụ tải lên thay vì sử dụng trình xử lý hoàn thành. Xem Quản lý tải lên để biết thêm thông tin.

Thêm siêu dữ liệu tệp

Bạn cũng có thể bao gồm siêu dữ liệu khi tải tệp lên. Siêu dữ liệu này chứa các thuộc tính siêu dữ liệu tệp điển hình như name , sizecontentType (thường được gọi là loại MIME). Phương thức putFile: tự động suy ra loại nội dung từ phần mở rộng tên tệp NSURL , nhưng bạn có thể ghi đè loại được phát hiện tự động bằng cách chỉ định contentType trong siêu dữ liệu. Nếu bạn không cung cấp contentType và Cloud Storage không thể suy ra giá trị mặc định từ phần mở rộng tệp thì Cloud Storage sẽ sử dụng application/octet-stream . Xem phần Sử dụng siêu dữ liệu tệp để biết thêm thông tin về siêu dữ liệu tệp.

Nhanh

// Create storage reference
let mountainsRef = storageRef.child("images/mountains.jpg")

// Create file metadata including the content type
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"

// Upload data and metadata
mountainsRef.putData(data, metadata: metadata)

// Upload file and metadata
mountainsRef.putFile(from: localFile, metadata: metadata)
    

Mục tiêu-C

// Create storage reference
FIRStorageReference *mountainsRef = [storageRef child:@"images/mountains.jpg"];

// Create file metadata including the content type
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = @"image/jpeg";

// Upload data and metadata
FIRStorageUploadTask *uploadTask = [mountainsRef putData:data metadata:metadata];

// Upload file and metadata
uploadTask = [mountainsRef putFile:localFile metadata:metadata];
  

Quản lý tải lên

Ngoài việc bắt đầu tải lên, bạn có thể tạm dừng, tiếp tục và hủy tải lên bằng các phương thức pause , resumecancel . Các phương thức này tăng các sự kiện pause , resumecancel . Việc hủy tải lên khiến quá trình tải lên không thành công kèm theo lỗi cho biết quá trình tải lên đã bị hủy.

Nhanh

// Start uploading a file
let uploadTask = storageRef.putFile(from: localFile)

// Pause the upload
uploadTask.pause()

// Resume the upload
uploadTask.resume()

// Cancel the upload
uploadTask.cancel()
    

Mục tiêu-C

// Start uploading a file
FIRStorageUploadTask *uploadTask = [storageRef putFile:localFile];

// Pause the upload
[uploadTask pause];

// Resume the upload
[uploadTask resume];

// Cancel the upload
[uploadTask cancel];
  

Theo dõi tiến trình tải lên

Bạn có thể đính kèm người quan sát vào FIRStorageUploadTask để theo dõi tiến trình tải lên. Việc thêm người quan sát sẽ trả về FIRStorageHandle có thể được sử dụng để xóa người quan sát.

Nhanh

// Add a progress observer to an upload task
let observer = uploadTask.observe(.progress) { snapshot in
  // A progress event occured
}
    

Mục tiêu-C

// Add a progress observer to an upload task
FIRStorageHandle observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress
                                              handler:^(FIRStorageTaskSnapshot *snapshot) {
                                                // A progress event occurred
                                              }];
  

Những người quan sát này có thể được thêm vào sự kiện FIRStorageTaskStatus :

Sự kiện FIRStorageTaskStatus Cách sử dụng điển hình
FIRStorageTaskStatusResume Sự kiện này kích hoạt khi tác vụ bắt đầu hoặc tiếp tục tải lên và thường được sử dụng cùng với sự kiện FIRStorageTaskStatusPause .
FIRStorageTaskStatusProgress Sự kiện này kích hoạt bất kỳ lúc nào dữ liệu đang được tải lên Cloud Storage và có thể được dùng để điền vào chỉ báo tiến trình tải lên.
FIRStorageTaskStatusPause Sự kiện này kích hoạt bất cứ khi nào quá trình tải lên bị tạm dừng và thường được sử dụng cùng với sự kiện FIRStorageTaskStatusResume .
FIRStorageTaskStatusSuccess Sự kiện này xảy ra khi quá trình tải lên hoàn tất thành công.
FIRStorageTaskStatusFailure Sự kiện này xảy ra khi quá trình tải lên không thành công. Kiểm tra lỗi để xác định lý do lỗi.

Khi một sự kiện xảy ra, một đối tượng FIRStorageTaskSnapshot sẽ được truyền trở lại. Ảnh chụp nhanh này là chế độ xem bất biến của nhiệm vụ tại thời điểm sự kiện xảy ra. Đối tượng này chứa các thuộc tính sau:

Tài sản Kiểu Sự miêu tả
progress NSProgress Một đối tượng NSProgress chứa tiến trình tải lên.
error NSError Đã xảy ra lỗi trong quá trình tải lên, nếu có.
metadata FIRStorageMetadata Trong quá trình tải lên có chứa siêu dữ liệu đang được tải lên. Sau sự kiện FIRTaskStatusSuccess , chứa siêu dữ liệu của tệp đã tải lên.
task FIRStorageUploadTask Nhiệm vụ này là ảnh chụp nhanh, có thể được sử dụng để quản lý ( pause , resume , cancel ) nhiệm vụ.
reference FIRStorageReference Các tài liệu tham khảo nhiệm vụ này đến từ.

Bạn cũng có thể xóa người quan sát, riêng lẻ, theo trạng thái hoặc bằng cách xóa tất cả chúng.

Nhanh

// Create a task listener handle
let observer = uploadTask.observe(.progress) { snapshot in
  // A progress event occurred
}

// Remove an individual observer
uploadTask.removeObserver(withHandle: observer)

// Remove all observers of a particular status
uploadTask.removeAllObservers(for: .progress)

// Remove all observers
uploadTask.removeAllObservers()
    

Mục tiêu-C

// Create a task listener handle
FIRStorageHandle observer = [uploadTask observeStatus:FIRStorageTaskStatusProgress
                                              handler:^(FIRStorageTaskSnapshot *snapshot) {
                                                // A progress event occurred
                                              }];

// Remove an individual observer
[uploadTask removeObserverWithHandle:observer];

// Remove all observers of a particular status
[uploadTask removeAllObserversForStatus:FIRStorageTaskStatusProgress];

// Remove all observers
[uploadTask removeAllObservers];
  

Để tránh rò rỉ bộ nhớ, tất cả trình quan sát sẽ bị xóa sau khi FIRStorageTaskStatusSuccess hoặc FIRStorageTaskStatusFailure xảy ra.

Xử lý lỗi

Có một số lý do khiến lỗi có thể xảy ra khi tải lên, bao gồm cả tệp cục bộ không tồn tại hoặc người dùng không có quyền tải tệp mong muốn lên. Bạn có thể tìm thêm thông tin về lỗi trong phần Xử lý lỗi của tài liệu.

Ví dụ đầy đủ

Dưới đây là một ví dụ đầy đủ về quá trình tải lên có theo dõi tiến trình và xử lý lỗi:

Nhanh

// Local file you want to upload
let localFile = URL(string: "path/to/image")!

// Create the file metadata
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"

// Upload file and metadata to the object 'images/mountains.jpg'
let uploadTask = storageRef.putFile(from: localFile, metadata: metadata)

// Listen for state changes, errors, and completion of the upload.
uploadTask.observe(.resume) { snapshot in
  // Upload resumed, also fires when the upload starts
}

uploadTask.observe(.pause) { snapshot in
  // Upload paused
}

uploadTask.observe(.progress) { snapshot in
  // Upload reported progress
  let percentComplete = 100.0 * Double(snapshot.progress!.completedUnitCount)
    / Double(snapshot.progress!.totalUnitCount)
}

uploadTask.observe(.success) { snapshot in
  // Upload completed successfully
}

uploadTask.observe(.failure) { snapshot in
  if let error = snapshot.error as? NSError {
    switch (StorageErrorCode(rawValue: error.code)!) {
    case .objectNotFound:
      // File doesn't exist
      break
    case .unauthorized:
      // User doesn't have permission to access file
      break
    case .cancelled:
      // User canceled the upload
      break

    /* ... */

    case .unknown:
      // Unknown error occurred, inspect the server response
      break
    default:
      // A separate error occurred. This is a good place to retry the upload.
      break
    }
  }
}
    

Mục tiêu-C

// Local file you want to upload
NSURL *localFile = [NSURL URLWithString:@"path/to/image"];

// Create the file metadata
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = @"image/jpeg";

// Upload file and metadata to the object 'images/mountains.jpg'
FIRStorageUploadTask *uploadTask = [storageRef putFile:localFile metadata:metadata];

// Listen for state changes, errors, and completion of the upload.
[uploadTask observeStatus:FIRStorageTaskStatusResume handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload resumed, also fires when the upload starts
}];

[uploadTask observeStatus:FIRStorageTaskStatusPause handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload paused
}];

[uploadTask observeStatus:FIRStorageTaskStatusProgress handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload reported progress
  double percentComplete = 100.0 * (snapshot.progress.completedUnitCount) / (snapshot.progress.totalUnitCount);
}];

[uploadTask observeStatus:FIRStorageTaskStatusSuccess handler:^(FIRStorageTaskSnapshot *snapshot) {
  // Upload completed successfully
}];

// Errors only occur in the "Failure" case
[uploadTask observeStatus:FIRStorageTaskStatusFailure handler:^(FIRStorageTaskSnapshot *snapshot) {
  if (snapshot.error != nil) {
    switch (snapshot.error.code) {
      case FIRStorageErrorCodeObjectNotFound:
        // File doesn't exist
        break;

      case FIRStorageErrorCodeUnauthorized:
        // User doesn't have permission to access file
        break;

      case FIRStorageErrorCodeCancelled:
        // User canceled the upload
        break;

      /* ... */

      case FIRStorageErrorCodeUnknown:
        // Unknown error occurred, inspect the server response
        break;
    }
  }
}];
  

Bây giờ bạn đã tải tệp lên, hãy tìm hiểu cách tải chúng xuống từ Cloud Storage.