在 iOS 上上传文件

Cloud Storage 可让开发者向 Firebase 提供和管理的 Google 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
  

您无法通过对您的 Google Cloud Storage 存储分区根目录的引用来上传数据。您的引用必须指向一个子网址。

上传文件

有了引用之后,您可以通过两种方式将文件上传到 Cloud Storage:

  1. 从内存中的数据上传
  2. 从代表设备上某个文件的网址上传

从内存中的数据上传

putData:metadata:completion: 方法是将文件上传到 Cloud Storage 的最简单方法。putData:metadata:completion: 可接受 NSData 对象并返回 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,它可用于管理上传并监控其状态。

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.
  storageRef.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: 方法并观察上传任务,而不是使用 completion 处理程序。如需了解详情,请参阅管理上传

添加文件元数据

在上传文件时,您还可以包括元数据。这些元数据包括典型的文件元数据属性,如 namesizecontentType(通常称为 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];
  

管理上传

除了启动上传外,您还可以分别使用 pauseresumecancel 方法来暂停、恢复和取消上传。这些方法会引发 pauseresumecancel 事件。取消上传会导致上传失败,并显示一条错误说明上传已被取消。

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

为了防止内存泄漏,所有观察者会在发生 FIRStorageTaskStatusSuccessFIRStorageTaskStatusFailure 后被移除。

错误处理

导致上传时出现错误的原因有很多,包括本地文件不存在,或者用户不具备上传所需文件的权限。如需了解有关错误的详情,请参阅相关文档的处理错误部分。

完整示例

下面是一个包含进度监控和错误处理的完整上传示例:

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 下载文件

发送以下问题的反馈:

此网页
需要帮助?请访问我们的支持页面