【问题标题】:how to upload file like pdf or doc in firestore如何在firestore中上传pdf或doc等文件
【发布时间】:2019-01-31 09:50:38
【问题描述】:

我想使用 redux 将文档文件上传到 firestore。我获取文件并将其作为状态传递给带有其他数据的操作文件。以下是我在操作文件中的代码。

const createJob = (project) => {
return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firestore = getFirestore();

    firestore.collection('Jobs').add({
        ...project,
        postedby:'Employer1',
        Documents:project.Documents.name
    }).then(()=>{
        dispatch({type:'CREATE_JOB', project});
    }).catch((err)=>{
        dispatch({type:'CREATE_JOB_ERROR', err});
    })
}
};

但数据保存为 C:\fakepath\doc1.doc

如何在firestore中上传实际文件

【问题讨论】:

    标签: reactjs redux react-redux google-cloud-firestore


    【解决方案1】:

    从技术上讲,您可以将图像上传到 Firestore。您需要先将其转换为 base64 文本。只是花了一些时间弄清楚。我从浏览器的上传文件中获取选定的文件,然后在文件阅读器的回调中上传它。希望这可以帮助某人。

    function getBase64(file){
         var n = document.getElementById('nameU').value;
        //name of uploaded file from textbox
         var d = document.getElementById('dateU').value;
        //date of uploaded file from textbox
        var reader = new FileReader();
        reader.onerror = function (error) {
           console.log('Error: ', error);
        };
        reader.readAsDataURL(file);
        reader.onload = function () {
            let encoded = reader.result.split(',');
            //you split this to get mimetype out of your base64
            addForSale(Date.now().toString(10), {uDesc: n, date: d, uFile: encoded[1]});
            // I just used a timestamp as the ID
        }
    };
    
    function addForSale(id, data) {
        var collection = firebase.firestore().collection('forsale');
        return collection.doc(id).set(data);}
    

    【讨论】:

      【解决方案2】:

      您好,您不能直接将图像存储在 firestore。您需要先将文档存储在 firebase 存储中并获取 url 作为响应。收到响应后,将 url 添加到文档中。

      首先在reduce中创建一个Storage Action:

      import { storage } from '../../../firebase/firebase';
      import {
        ADD_DOCUMENT_STARTED,
        ADD_DOCUMENT_COMPLETED,
        ADD_DOCUMENT_ERROR
      } from '../../actionTypes/storageActionTypes';
      import { toast } from 'react-toastify';
      import constants from '../../../config/constants';
      
      export const addDocumentStart = () => ({
        type: ADD_DOCUMENT_STARTED
      });
      export const addDocumentSuccess = () => ({
        type: ADD_DOCUMENT_COMPLETED
      });
      export const addDocumentFailure = () => ({
        type: ADD_DOCUMENT_ERROR
      });
      
      export const addDocument = (values, pathName) => {
        const toastId = toast('Uploading Attachment, Please wait..', {
          autoClose: false
        });
        return (dispatch) =>
          new Promise(function(resolve, reject) {
            dispatch(addDocumentStart());
            const timeStamp = new Date().getTime();
            const image = values.document[0];
            var name;
            if (values && values.documentName) {
              name = timeStamp.toString().concat(values.documentName);
            } else {
              name = timeStamp.toString().concat(image.name);
            }
            const imageUpload = storage.ref(`${pathName}/${name}`).put(image);
            imageUpload.on(
              'state_changed',
              (snapshot) => {
                switch (snapshot.state) {
                  case 'paused':
                    reject('Upload is paused');
                    dispatch(addDocumentFailure('Upload is paused'));
                    break;
                }
              },
              (error) => {
                switch (error.code) {
                  case 'storage/unauthorized':
                    reject('Permission Denied');
                    dispatch(addDocumentFailure('Permission Denied'));
                    break;
                  case 'storage/canceled':
                    reject('Upload Cancelled');
                    dispatch(addDocumentFailure('Upload Cancelled'));
                    break;
                  case 'storage/unknown':
                    reject('Server Response Error');
                    dispatch(addDocumentFailure('Server Response Error'));
                    break;
                }
              },
              () => {
                toast.update(toastId, {
                  render: 'Attachment Uploaded successfully',
                  type: toast.TYPE.SUCCESS,
                  autoClose: constants.toastTimer
                });
                storage
                  .ref(pathName)
                  .child(name)
                  .getDownloadURL()
                  .then((url) => {
                    dispatch(addDocumentSuccess());
                    resolve(url);
                  });
              }
            );
          });
      };
      

      然后在您的 onsubmit 中:

       this.props.dispatch(addDocument(values, 'Jobs')).then((resp) => {
        let documentUrl = resp;
        firestore.collection('Jobs').add({
                ...project,
                postedby:'Employer1',
                Documents:documentUrl
            }).then(()=>{
      });
      

      【讨论】:

      • 您提到的 onsubmit 是一个 redux 操作文件,其中我已经有一个函数 createJob .... 我应该在其中包含上述内容吗?我还有 2 个其他减速器。我应该将 addDocument 减速器与它结合起来吗?请让我理解
      • 不,这是您的 createJob redux 操作
      猜你喜欢
      • 2020-06-22
      • 2021-08-03
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      相关资源
      最近更新 更多