Apple 平台上使用 Cloud Storage 上傳文件

Cloud Storage for Firebase 讓您可以快速輕鬆地將檔案上傳到由 Firebase 提供和管理的Cloud Storage 儲存桶。

建立參考

若要上傳文件,請先建立對 Cloud Storage 中要將文件上傳到的位置的 Cloud Storage 引用

您可以透過將子路徑附加到 Cloud Storage 儲存桶的根來建立參考:

迅速

// 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
    

Objective-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
  

您無法上傳引用 Cloud Storage 儲存分區根的資料。您的引用必須指向子 URL。

上傳文件

獲得參考後,您可以透過兩種方式將檔案上傳到 Cloud Storage:

  1. 從記憶體中的資料上傳
  2. 從代表裝置上文件的 URL 上傳

從記憶體中的資料上傳

putData:metadata:completion:方法是將檔案上傳到 Cloud Storage 的最簡單方法。 putData:metadata:completion:接受一個 NSData 物件並傳回一個FIRStorageUploadTask ,您可以使用它來管理上傳並監控其狀態。

迅速

// 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
    }
  }
}
    

Objective-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;
      }
    }];
  }
}];
  

從本機檔案上傳

您可以使用putFile:metadata:completion:方法上傳裝置上的本機文件,例如相機中的照片和影片。 putFile:metadata:completion:接受NSURL並傳回FIRStorageUploadTask ,您可以使用它來管理上傳並監控其狀態。

迅速

// 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
    }
  }
}
    

Objective-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;
      }
    }];
  }
}];
  

如果您想主動管理上傳,可以使用putData:putFile:方法並觀察上傳任務,而不是使用完成處理程序。有關更多信息,請參閱管理上傳

新增檔案元數據

您也可以在上傳文件時包含元資料。此元資料包含典型的檔案元資料屬性,例如namesizecontentType (通常稱為 MIME 類型)。 putFile:方法會自動從NSURL檔案副檔名推斷內容類型,但您可以透過在元資料中指定contentType來覆寫自動偵測的類型。如果您不提供contentType且 Cloud Storage 無法從檔案副檔名推斷出預設值,Cloud Storage 將使用application/octet-stream 。有關文件元資料的更多信息,請參閱使用文件元資料部分。

迅速

// 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)
    

Objective-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];
  

管理上傳

除了開始上傳之外,您還可以使用pause 、resume和cancel方法暫停、 resume和取消上傳。這些方法引發pauseresumecancel事件。取消上傳會導致上傳失敗,並顯示錯誤,指示上傳已取消。

迅速

// 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()
    

Objective-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];
  

監控上傳進度

您可以將觀察者附加到FIRStorageUploadTask以監視上傳進度。新增觀察者會傳回一個FIRStorageHandle ,可用於刪除觀察者。

迅速

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

Objective-C

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

這些觀察者可以加入FIRStorageTaskStatus事件中:

FIRStorageTaskStatus事件典型用法
FIRStorageTaskStatusResume此事件在任務開始或復原上傳時觸發,通常與FIRStorageTaskStatusPause事件結合使用。
FIRStorageTaskStatusProgress每當資料上傳到 Cloud Storage 時都會觸發此事件,並可用於填入上傳進度指示器。
FIRStorageTaskStatusPause每當上傳暫停時都會觸發此事件,並且通常與FIRStorageTaskStatusResume事件結合使用。
FIRStorageTaskStatusSuccess當上傳成功完成時會觸發此事件。
FIRStorageTaskStatusFailure當上傳失敗時觸發此事件。檢查錯誤以確定失敗原因。

當事件發生時,會傳回一個FIRStorageTaskSnapshot物件。此快照是事件發生時任務的不可變視圖。該物件包含以下屬性:

財產類型描述
progress NSProgress包含上傳進度的NSProgress物件。
error NSError上傳期間發生的錯誤(如果有)。
metadata FIRStorageMetadata上傳期間包含正在上傳的元資料。在FIRTaskStatusSuccess事件之後,包含上傳檔案的元資料。
task FIRStorageUploadTask這是任務的快照,可用於管理( pauseresumecancel )任務。
reference FIRStorageReference該任務來自的參考。

您也可以按狀態單獨刪除觀察者,或刪除全部觀察者。

迅速

// 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()
    

Objective-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];
  

為了防止記憶體洩漏,在發生FIRStorageTaskStatusSuccessFIRStorageTaskStatusFailure後,將刪除所有觀察者。

錯誤處理

上傳錯誤的原因有很多,包括本機檔案不存在,或是使用者沒有上傳所需檔案的權限。您可以在文件的處理錯誤部分找到有關錯誤的更多資訊。

完整範例

具有進度監控和錯誤處理功能的上傳的完整範例如下所示:

迅速

// 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
    }
  }
}
    

Objective-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;
    }
  }
}];
  

現在您已經上傳了文件,讓我們了解如何從 Cloud Storage下載它們