![](/img/trans.png)
[英]How to upload an image file to Firebase Storage and show it in the Flutter web app
[英]How to upload a file to Firebase in an iOS app (Swift)
我使用这个答案https://stackoverflow.com/a/64168754/16212254作为参考,允许用户选择一个文件,但现在我不知道如何将文件上传到 Firebase。我是 Swift 的新手,拜托别介意我的愚蠢问题。
我试图按照https://firebase.google.com/docs/firestore/quickstart#ios和https://firebase.google.com/docs/storage/ios/upload-files但仍然无法弄清楚如何发送将文件发送到 firebase,因为我不知道附件的名称和路径。
您过去能够选择文件的答案工作正常,但没有在didFinishPickingMediaWithInfo
和didPickDocumentsAt
函数的 scope 之外提供对所选图像或文件的引用。
以下是保存文件/图像数据以便日后访问的方法。
创建Data?
在你的 ViewController 中。
var myData: Data?
如果您正在处理图像,在didFinishPickingMediaWithInfo
function 中,将所选图像的 png 数据保存在新创建的变量中(其中 scope 不限于函数本身)。 如果您改为处理文件,请在didPickDocumentAt
function 中执行基本相同的操作。
// Image
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
// The following 2 lines don't actually do anything: the selectedImageData dictionary
// ceases existing as soon as the functions ends
// selectedImageData["filename"] = fileUrl.lastPathComponent
// selectedImageData["data"] = pickedImage.pngData()?.base64EncodedString(options: .lineLength64Characters)
self.myData = pickedImage.pngData()
}
// File
do {
let fileData = try Data.init(contentsOf: file.absoluteURL)
// The following 2 lines don't actually do anything: the selectedFileData dictionary
// ceases existing as soon as the functions ends
// selectedFileData["filename"] = file.lastPathComponent
// selectedFileData["data"] = fileData.base64EncodedString(options: .lineLength64Characters)
self.myData = fileData
} catch {
// ...
}
然后,要将数据上传到 Firebase Storage,可以使用以下 function:
import FirebaseStorage // At the beginning of the file
// Uploads the selected image/file data there is any.
func uploadSavedData() {
guard let data = myData else { return } // Checks whether there is actual data to upload.
let storageRef = Storage.storage().reference()
let fileRef = storageRef.child("userUID/files/documentName.png")
let uploadTask = fileRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else { return } // Cancels task if there is any error
fileRef.downloadURL { (url, error) in {
guard let downloadURL = url else { return }
print(downloadURL) // Prints the URL to the newly uploaded data.
}
}
}
有关该主题的更多资源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.