Cloud Storage สำหรับ Firebase ช่วยให้คุณอัปโหลดไฟล์ไปยังที่ฝากข้อมูล Cloud Storage ที่ Firebase จัดเตรียมและจัดการได้อย่างรวดเร็วและง่ายดาย
สร้างข้อมูลอ้างอิง
หากต้องการอัปโหลดไฟล์ ก่อนอื่น ให้สร้างการอ้างอิง 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
วัตถุประสงค์-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 } } }
วัตถุประสงค์-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 } } }
วัตถุประสงค์-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)
วัตถุประสงค์-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
กิจกรรม การยกเลิกการอัปโหลดจะทำให้การอัปโหลดล้มเหลวโดยมีข้อผิดพลาดระบุว่าการอัปโหลดถูกยกเลิก
สวิฟต์
// 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()
วัตถุประสงค์-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 }
วัตถุประสงค์-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()
วัตถุประสงค์-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 } } }
วัตถุประสงค์-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 กัน