簡體   English   中英

如何在Firebase存儲器中存儲圖像並將鏈接保存到數據庫中?

[英]How to store images in firebase storage and save link to them on database?

我到處尋找答案。 我最近的人在這里 ,但是,它並不能完全回答我的問題。 也就是說,如何在數據庫中存儲對保存在Firebase存儲中的圖像的引用。

以下是我嘗試過的代碼。 上傳時它可以存儲一張圖像,但是我不確定這是否意味着存儲參考。

if let imageData = UIImageJPEGRepresentation(image, 0.8) {
    let metadata = storageRef //.child("poop/")

    let uploadTask = metadata.putData(imageData, metadata: nil) {
         (metadata, error) in
        guard let metadata = metadata else {
            // Uh-oh, an error occurred!
            return
        }

        // 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
            }
            //let imgURL = url

            //database integration
            let ref = Database.database().reference()
            let usersRef = ref.child("usersPosts")

            let uid = Auth.auth().currentUser?.uid
            let newUserRef = usersRef.child(uid!)
            //creates a child for email and password (i think we shud store password so we can tell sumone what it is inmediatly, maybe)
            newUserRef.setValue(["Image": "\(downloadURL)"])
        }

    }

    //            let imgURL = storageRef.downloadURL
    //
    //            //database integration
    //            let ref = Database.database().reference()
    //            let usersRef = ref.child("usersPosts")
    //
    //            let uid = Auth.auth().currentUser?.uid
    //            let newUserRef = usersRef.child(uid!)
    //            //creates a child for email and password (i think we shud store password so we can tell sumone what it is inmediatly, maybe)
    ////                newUserRef.setValue(["Image": "\(imgURL)"])





    // For progress
    uploadTask.observe(.progress, handler: { (snapshot) in
        guard let progress = snapshot.progress else {
        return
    }

    let percentage = (Float(progress.completedUnitCount) / Float(progress.totalUnitCount))
    progressBlock(Double(percentage))
    })

} else {
    completionBlock(nil, "Image could not be converted to Data.")
}

感謝您的幫助!

請根據需要修改您的代碼

var imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.img_Photo?.image)!, 0.8)!)
self.uploadProfileImageToFirebase(data: imgData)


func uploadProfileImageToFirebase(data:NSData){
    let storageRef = Storage.storage().reference().child("usersPosts").child("\(uid).jpg")
    if data != nil {
        storageRef.putData(data as Data, metadata: nil, completion: { (metadata, error) in
            if(error != nil){
                print(error)
                return
            }
            guard let userID = Auth.auth().currentUser?.uid else {
                return
            }
            // Fetch the download URL
            storageRef.downloadURL { url, error in
                if let error = error {
                    // Handle any errors
                    if(error != nil){
                        print(error)
                        return
                    }
                } else {
                    // Get the download URL for 'images/stars.jpg'

                    let urlStr:String = (url?.absoluteString) ?? ""
                    let values = ["downloadURL": urlStr]
                    self.addImageURLToDatabase(uid: userID, values: values as [String : AnyObject])
                }
            }
        })
    }

}


func addImageURLToDatabase(uid:String, values:[String:AnyObject]){
    let ref = Database.database().reference(fromURL: "https://exampleapp.firebaseio.com/")
    let usersReference = ref.child("usersPosts").child((Auth.auth().currentUser?.uid)!)

    usersReference.updateChildValues(values) { (error, ref) in
        if(error != nil){
            print(error)
            return
        }
        self.parentVC?.dismiss(animated: true, completion: nil)
    }

}
(TS)  
onFileChanged(param){    
var aa;    
const file: File = param.target.files[0];  
const metaData = { 'contentType': file.type };    
const StorageRef: firebase.storage.Reference = firebase.storage().ref('/photos/Category/'+this.CategoryName);    
const Store = StorageRef.put(file, metaData);
setTimeout(() => {
const UP: firebase.storage.UploadTask = Store;
 UP.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log('File available at', downloadURL);
aa = downloadURL;
});
}, 1000);

setTimeout(() => {
this.ImageLink = aa;
debugger;
}, 2000);

IN HTML

type="file" accept="image/*" #file style="display: none">
<img (click)="file.click()" style="margin-left: 10%"src="http://icons.iconarchive.com/icons/icons8/windows-8/512/Photo-Video-Stack-Of-Photos-icon.png" width="50px" />

將*作為Firebase導入為'@ ionic / firebase'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM