Cloud Storage for Firebase 可讓您快速輕鬆地將檔案上傳至 Firebase 提供並管理的 Cloud Storage 儲存體。
可建立參照
如要上傳檔案,請先建立 Cloud Storage 參照,指向您要上傳檔案的 Cloud Storage 位置。
您可以將子路徑附加至 Cloud Storage 桶的根目錄,藉此建立參照:
Swift
// 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 值區根目錄的資料。參照項目必須指向子網址。
上傳檔案
取得參照後,您可以透過兩種方式將檔案上傳至 Cloud Storage:
- 從記憶體中的資料上傳
- 從代表裝置上檔案的網址上傳
從記憶體中的資料上傳
putData:metadata:completion:
方法是將檔案上傳至 Cloud Storage 最簡單的方式。putData:metadata:completion:
會接收 NSData 物件並傳回 FIRStorageUploadTask
,您可以使用 FIRStorageUploadTask
管理上傳內容並監控其狀態。
Swift
// 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
,您可以使用 FIRStorageUploadTask
管理上傳作業並監控其狀態。
Swift
// 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:
方法並觀察上傳工作,而非使用完成處理常式。詳情請參閱「管理上傳內容」。
新增檔案中繼資料
您也可以在上傳檔案時加入中繼資料。這項中繼資料包含一般檔案中繼資料屬性,例如 name
、size
和 contentType
(通常稱為 MIME 類型)。putFile:
方法會自動從 NSURL
檔案名稱副檔名推斷內容類型,但您可以在中繼資料中指定 contentType
,藉此覆寫自動偵測的類型。如果您沒有提供 contentType
,且 Cloud Storage 無法從副檔名推斷預設值,Cloud Storage 會使用 application/octet-stream
。如要進一步瞭解檔案中繼資料,請參閱「使用檔案中繼資料」一節。
Swift
// 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
方法暫停、繼續及取消上傳作業。這些方法會觸發 pause
、resume
和 cancel
事件。取消上傳會導致上傳失敗,並顯示上傳已取消的錯誤訊息。
Swift
// 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
,可用於移除觀察器。
Swift
// 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 |
這是工作快照,可用於管理 (pause 、resume 、cancel ) 工作。 |
reference |
FIRStorageReference |
這項工作的參照來源。 |
您也可以依狀態個別移除觀察者,或是一次移除所有觀察者。
Swift
// 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];
為避免記憶體流失,系統會在 FIRStorageTaskStatusSuccess
或 FIRStorageTaskStatusFailure
發生後移除所有觀察器。
處理錯誤
上傳時可能發生錯誤的原因有很多,包括本機檔案不存在,或是使用者沒有權限上傳所需檔案。如要進一步瞭解錯誤,請參閱說明文件的「處理錯誤」一節。
完整範例
以下是上傳內容的完整範例,其中包含進度監控和錯誤處理功能:
Swift
// 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下載檔案。