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:
- 從內存中的數據上傳
- 從代表設備上文件的 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:
方法並觀察上傳任務,而不是使用完成處理程序。有關更多信息,請參閱管理上傳。
添加文件元數據
您還可以在上傳文件時包含元數據。此元數據包含典型的文件元數據屬性,例如name
、 size
和contentType
(通常稱為 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
方法pause
、 resume
和取消上傳。這些方法引發pause
、 resume
和cancel
事件。取消上傳會導致上傳失敗,並顯示錯誤,指示上傳已取消。
迅速
// 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 | 這是任務的快照,可用於管理( pause 、 resume 、 cancel )任務。 |
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];
為了防止內存洩漏,在發生FIRStorageTaskStatusSuccess
或FIRStorageTaskStatusFailure
後,將刪除所有觀察者。
錯誤處理
上傳錯誤的原因有很多,包括本地文件不存在,或者用戶沒有上傳所需文件的權限。您可以在文檔的處理錯誤部分找到有關錯誤的更多信息。
完整示例
具有進度監控和錯誤處理功能的上傳的完整示例如下所示:
迅速
// 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下載它們。