如何在Firestore中上传pdf或doc之类的文件

时间:2019-01-31 09:50:39

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

我想使用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中上传实际文件

2 个答案:

答案 0 :(得分: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);}

答案 1 :(得分:0)

嗨,您不能将图像直接存储在firestore中。您要做的是首先将文档存储在firebase存储中,并获得url作为响应。一旦收到响应,请将url添加到文档中。

首先在reduce中创建一个存储操作:

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);
            });
        }
      );
    });
};

然后在您的提交中:

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