【问题标题】:Uploading Images to Firebase from VueJs app从 VueJs 应用程序将图像上传到 Firebase
【发布时间】:2019-04-01 05:57:37
【问题描述】:

我想让用户在同一个活动中注册并上传一张图片,所以姓名和电子邮件等数据将进入 firestore,而图片将进入存储桶,目前,我能够实现这两个功能,但分开,所以我有点坚持的是如何将数据和图像链接在一起,以便我以后可以检索它们。我也想用 Vuex 来完成。下面的代码解释了我如何将数据和图像分别从我的 .vue 组件发送到 firestore 和 storage

import { storage } from '../firebase/init.js'
import firebase from 'firebase'

export default {
  data(){
    return {
        email: '',
        password: '',
        image: null
      }
    }, 
    methods: {
      signUp(){
        firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
           .then(response => {
             let user = {
             id: response.user.id,
             email: response.user.email
           }
          //here i want to do something to link this user to the upload image event below
        })
      },
      uploadFile(e){
        const file = e.target.files[0];
        
        storage.ref('images/'+ file.name).put(file)
          .then(response => {
            console.log(response)
          })
          .catch(err => console.log(err))
      }
    }
    

请在下方留言以作进一步说明,在此先感谢

【问题讨论】:

  • 为什么不在存储引用路径中包含用户id?喜欢images/${userId}/${file.name}
  • 实际上我确实尝试过它并且它有效,所以现在我将信息发送到我的 Firestore 集合,然后上传带有响应 ID 的图像,在此处检查代码 codesandbox,现在,你有任何想法如何在应用程序中检索和呈现它吗?无论如何谢谢:)

标签: firebase vue.js firebase-authentication google-cloud-firestore vuex


【解决方案1】:

您需要获取 firebase 以返回图像的 url,然后将其作为字段插入到您的数据库中。试试这样的:

uploadFile(e){
    const file = e.target.files[0];
    storage.ref('images/'+ file.name).put(file)
      .then(response => {
        response.ref.getDownloadURL().then((downloadURL) => {
           firebase.database().ref(YOUR_DATABASE).child(THE_USER_ID).update({imageUrl:downloadURL})
      }                 
     .catch(err => console.log(err))
}

这应该将图像 url 插入数据库中,然后您可以在调用所有用户数据时调用它。

【讨论】:

  • 我在 YOUR_DATABASE 和 THE_USER_ID 字段中输入了什么?我从哪里获得相关信息?
  • @IkechukwuAnude,YOUR_DATABASE 是您在 firebase 上创建的数据库的名称。不管你怎么称呼它。 THE_USER_ID 是您要更新的记录的唯一标识符。在上述问题中,OP 想要将上传图像的路径链接到用户,因此使用了用户 ID。您的用例可能会有所不同,如果您要上传与博客文章相关的图片,您将使用文章 ID。
【解决方案2】:
createNewProperty({commit, getters, state}, payload) {
  commit('setLoading', true)
  const newService = {
    name : payload.name,
    PropertyMap: payload.PropertyMap,
    location : payload.Location,
    AboutProperty: payload.AboutProperty
  }
  var dropName = ''
  //Check If Service Exists
  firebase.firestore().collection('CompanyMenu')
  .where('name','==',payload.name)
  .where('location','==',payload.Location)
  .get()
  .then(service=>{
    if(service.size == 0) {
      let key
      let imageUrl

      firebase.firestore().collection('properties')
        .add(newService)
        .then( (data)=>{
          key = data.id
          return key
        }).then(key=>{
          const filename = payload.Image.name
          const ext = filename.slice(filename.lastIndexOf('.'))
          dropName = key +'.'+ext

          var uploadTask = firebase.storage().ref('properties/'+ key +'.'+ext).put(payload.Image)
          uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, 
            function(snapshot) {

              var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
              commit('setUploading', progress)
              console.log('Upload is ' + progress + '% done');
              switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED: // or 'paused'
                  console.log('Upload is paused');
                  break;
                case firebase.storage.TaskState.RUNNING: // or 'running'
                  console.log('Upload is running');
                  break;
              }
            },function(error) {
              switch (error.code) {
                case 'storage/unauthorized':
                  console.log('User doesn\'t have permission to access the object')
                  break;

                case 'storage/canceled':
                  console.log('User canceled the upload')
                  break;
                case 'storage/unknown':
                  console.log('Unknown error occurred, inspect error.serverResponse')
                  break;
              }
            },
            function() {
              uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
                console.log('File available at', downloadURL);
                firebase.firestore().collection('properties').doc(key).update({Image: downloadURL,filename: dropName})
                .then( (company)=>{
                  state.properties.push({
                    id: key,
                    Image: downloadURL,
                    filename: dropName,
                    ...newService
                  })
                  commit('setLoading', false)
                  this.$router.push('/Properties')

                } )

              })
          })
        })
    } else {//If Service Exists


    }

  })
}

此代码最适合我。我还添加了一个链接,以防您想从 Firebase 存储中删除文件

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 2016-11-20
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    相关资源
    最近更新 更多