Как сделать так, чтобы файл оставался после обновления на реактивной логике с помощью firebase - PullRequest
0 голосов
/ 24 декабря 2018

Я хотел, чтобы мой pdf оставался там до дальнейшей загрузки от администратора системы.Каждый раз, когда я обновляюсь или возвращаюсь на страницу, мой pdf пропадает, и мне нужно загрузить файл.

Я пытался использовать localStorage, sessionStorage и cookie.Но мне было предложено использовать только хранилище Firebase.

import React from 'react';
import { bindActionCreators} from 'redux'
import thunkMiddleware from 'redux-thunk'
import {connect} from 'react-redux';
import Immutable from 'immutable';
import { BrowserRouter, Link, Match, Redirect } from 'react-router';
import PDF from 'react-pdf-js';
import {fromJS, Map, List} from 'immutable';
import PropTypes from 'prop-types'
import throttle from "lodash.throttle"
import { Input } from 'antd'
import firebase from "firebase";
import {database} from '../actions/FirebaseUtils'
import FileUploader from "react-firebase-file-uploader";
import CustomUploadButton from 'react-firebase-file-uploader/lib/CustomUploadButton';
import * as HeaderActions from '../actions/HeaderActions'

class TeacherModuleContainer extends React.PureComponent {
  static propTypes = {
  firebase: PropTypes.object
  }
  constructor(props){
    super(props)
    this.state = {
      filenames: [],
      pdfUrl:[],
      downloadURLs: [],
      isUploading: false,
      uploadProgress: 0,
      lastEditedBy: null,
      width:null,
      lesson:{
        last_edited_by: this.props.userId || ''
      }
    }
    this.onChange = this.onChange.bind(this)
  }

  componentDidMount(){
    //
    this.setDivSize()
    window.addEventListener("resize", throttle(this.setDivSize, 500))

    this.props.getAdmins.getAdmins(this.props.programId)
    this.props.getAdmins.getOwners()
    this._isMounted = true
  }
  componentWillUnmount(){
    //pdf resize
    window.removeEventListener("resize", throttle(this.setDivSize, 500))

    this._isMounted = false
  }
//setting the position of the pdf
 setDivSize =()=>{
   this.setState({width: this.pdfWrapper.getBoundingClientRect().width})
 }
 //progress upload pdf js
 onChange(event) {
 this.setState({
   pdfUrl: URL.createObjectURL(event.target.file[0])
 })
}
 handleUploadStart = () =>
   this.setState({
     isUploading: true,
     uploadProgress: 0
   });
 handleProgress = progress =>
   this.setState({
     uploadProgress: progress
   });
 handleUploadError = error => {
   this.setState({
     isUploading: false
     // Todo: handle error
   });
   console.error(error);
   };
   //displaying the pdf
   handleUploadSuccess = async filename => {
   const downloadURL = await firebase
     .storage()
     .ref("pdf")
     .child(filename)
     //getDownloadUrl
     .getDownloadURL()
     .then (url => this.setState({pdfUrl:url})); // this is for upload the pdf
     this.setState(oldState => ({
     filenames: [...oldState.filenames, filename],
     downloadURLs: [...oldState.downloadURLs, downloadURL],
     uploadProgress: 100,
     isUploading: false
   }));
   };
    onDocumentComplete = (pages) => { // comes from react=pdf-js
    this.setState({ page: 1, pages });
   }
   //pagination of our PDF
   handlePrevious = () => {
     this.setState({ page: this.state.page - 1 });
   }
   handleNext = () => {
     this.setState({ page: this.state.page + 1 });
   }
   renderPagination = (page, pages) => {
     let previousButton = <p className="previous" onClick={this.handlePrevious}><button type="button" class="btn">&laquo; Previous</button></p>;
     if (page === 1) {
       previousButton = <p className="previous disabled"><button type="button" class="btn">&laquo; Previous</button></p>;
     }
     let nextButton = <p className="next" onClick={this.handleNext}><button type="button" class="btn">Next &raquo;</button></p>;
     if (page === pages) {
       nextButton = <p className="next disabled"><button type="button" class="btn">Next &raquo;</button></p>;
     }
     return (
        <nav>
          <p className="pager">
            {previousButton}
            {nextButton}
          </p>
        </nav>
        );
      }
    //our render
  render() {
     let pagination = null;
     if (this.state.pages) {
       pagination = this.renderPagination(this.state.page, this.state.pages);
     }
     return (
       <div id="row" style={{height: "150vh", width: "100vw", display: "flex", overflow: "hidden"}}>
       <div id="PDF" style={{width: "35vw", height: "150vh"}}/>
       <div id='pdfWrapper' style={{width:"90vw"} } ref={(ref)=>this.pdfWrapper = ref}>
       <label style={{backgroundColor: 'Orange', color: 'white', padding: 7, borderRadius: 1, pointer: 'cursor'}}>
       <FileUploader
            accept="application/pdf"
            name="pdf-uploader-multiple"
            randomizeFilename
            storageRef={firebase.storage().ref("pdf")}
            onUploadStart={this.handleUploadStart}
            onUploadError={this.handleUploadError}
            onUploadSuccess={this.handleUploadSuccess}
            onProgress={this.handleProgress}
            multiple
          />
          </label>
          <p>Progress: {this.state.uploadProgress}</p>
          {pagination}
         <PDF
           wrapperDivSize={this.state.width}
           file={this.state.pdfUrl}
          onChange={this.onChange}
           onDocumentComplete={this.onDocumentComplete}
           onUploadError={this.handleUploadError}
           page={this.state.page}
           scale={this.state.scale}
         />

       </div>
       </div>
     )
   }
 }

Я ожидаю, что PDF останется там до дальнейшей загрузки.Я не хочу использовать локальное хранилище.

...