FileUploadComponent.js 10 KB
import React, {Component} from 'react'

import ReactFileReader from 'react-file-reader';

import * as SelectActionCreators from '../../actions/profilationSelect'
import uploadIcon from '../../../img/upload.svg'
import camIcon from '../../../img/cam.svg'
import  LemaApi  from '../../../service/service.js';
import {connect} from 'react-redux';

function getFileExtension(filename) {
    return filename.split('.').pop();
}

function getBase64File(b64File) {
    return b64File.split(',').pop();
}

function getFileKind(fileKindAttr) {
    let fileKind;

    if (fileKindAttr == "idCard_front" || fileKindAttr == "idCard_back")
        fileKind = "carta_identita";
    if (fileKindAttr == "cfCard_front" || fileKindAttr == "cfCard_back")
        fileKind = "codice_fiscale";
    if (fileKindAttr == "lightBill")
        fileKind = "fattura_elettrica"
    if (fileKindAttr == "gasBill")
        fileKind = "fattura_gas"
    /*if (fileKindAttr == "cfCard_front" || fileKindAttr == "cfCard_back")
        fileKind = "pec_ricezione"*/

    return fileKind;
}

class FileUploadComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            stepIndex: this.props.stepIndex,
            name: this.props.name,
            
        }
        this.handleFiles = this.handleFiles.bind(this);

    }

    saveFile = (files, base64FileNotPure) => {
        //il primo elemento dell'array FileList è l'immagine che serve a Noi
        let request = {
            content_type: files.type,
            owner_description: files.name,
            sorting_rank: null,
            data_b64: getBase64File(base64FileNotPure)
        };
    
        const lemaApi = new LemaApi();
        var saveFileResponse = lemaApi.saveActivationFiles(request, getFileKind(this.props.name));
        
       return saveFileResponse;
    }
    
    snapPhoto(){
        /*
        navigator.getMedia = ( navigator.getUserMedia || // use the proper vendor prefix
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

        navigator.getMedia({video: true}, function() {
          this.props.showCamModal('CAM_MODAL', this.props.name, this.props.maxPhotos, this.state.stepIndex)
        }.bind(this), function() {
          this.props.showModal('NO_CAM_MODAL')
        }.bind(this));
        */

        try{
        navigator.mediaDevices.getUserMedia({video: true})
        .then(function(stream) {
          this.props.showCamModal('CAM_MODAL', this.props.name, this.props.maxPhotos, this.state.stepIndex)
        }.bind(this))
        .catch(function(err) {
          this.props.showModal('NO_CAM_MODAL')
        }.bind(this));

        }
        catch(err){
            this.props.showModal('NO_CAM_MODAL')
        }
        /*try{
            navigator.mediaDevices.getUserMedia({video: true}, function() {
              this.props.showCamModal('CAM_MODAL', this.props.name, this.props.maxPhotos, this.state.stepIndex)
            }.bind(this))
        }
        catch(err){
            this.props.showModal('NO_CAM_MODAL')
        }*/
    }

    handleFiles(files) {
        let base64FileNotPure = files.base64;
        let saveFileResponse = [];
        let idFile, idFilesCSV, propName, content;
        let sizeTnX = this.props.thumbNailInfo.size_x;
        let sizeTnY = this.props.thumbNailInfo.size_y;
        let TNoutputContentType = this.props.thumbNailInfo.outputContentType;

        files = files.fileList;

        var maxFiles = this.props.maxPhotos;
        if (this.props.activationSteps[this.state.stepIndex][this.props.name] !== '') {
            maxFiles = maxFiles - this.props.activationSteps[this.state.stepIndex][this.props.name].preview.length
        }

        for(let i = 0; i < files.length; i++)
            saveFileResponse.push(this.saveFile(files[i], base64FileNotPure[i]));

        this.props.updateStoreValue(this.props.name + '_fileNumberError', files.length > maxFiles)
        propName = this.props.name;

        var error = false
        var sizeError = false
        
        for(let i = 0; i < saveFileResponse.length; i++){

            saveFileResponse[i].then(function(res){
                console.log("file type: " + propName);
    
                idFile = res.file_info.id;
                content = res.file_info.content_type;
    
                let responseThumbNails = {
                    FileId: idFile,
                    Format: TNoutputContentType,
                    size_x: sizeTnX,
                    size_y: sizeTnY
                }
                    
                if (propName == 'lightBill' || propName == 'gasBill'){
                    idFilesCSV = localStorage.getItem(propName + '_idFile') == null ? "" : localStorage.getItem(propName + '_idFile');

                    if (idFilesCSV.length != 0)
                        localStorage.setItem(propName + '_idFile', idFilesCSV + ',' + idFile);
                    else
                        localStorage.setItem(propName + '_idFile', idFile);
                }
                else
                    localStorage.setItem(propName + '_idFile', idFile);
                
                //Carica l'unico (o il primo, in caso di file multipli caricati) file per il thumbnail
                //in caso di file multipli caricati, il thumbnail mi serve che venga generato solo di UN file
                if (i == 0){
                    const lemaApi = new LemaApi();
                    let base64ThumbNail = lemaApi.createThumbnails(responseThumbNails);
        
                    base64ThumbNail.then(function(res){
                        localStorage.setItem("thumbNailImg_" + idFile, "data:" + content + ";base64," + res.file.data_b64);
                        console.log("getItem: " + localStorage.getItem("thumbNailImg_" + idFile));
        
                    }).catch(function(err){
                        console.log("errore salvataggio thumbnail");
                    });
                }
            });        
        }

        for (var i = 0; (i < files.length && i < maxFiles); i++) {
            const ext = getFileExtension(files[i].name)
            if (ext === 'jpg' || ext === 'jpeg' || ext === 'JPG' || ext === 'JPEG' ||
                ext === 'png' || ext === 'PNG' ||
                ext === 'pdf' || ext === 'PDF' ||
                ext === 'zip' || ext === 'ZIP' ||
                ext === 'tiff' || ext === 'TIFF') {
                if(files[i].size/1048576<=this.props.maxFileSize){
                    this.props.previewFile(files[i])
                }
                else{
                    sizeError=true
                }

            } else {

                error = true
            }

        }

        this.props.updateStoreValue(this.props.name + '_fileSizeError', sizeError)
        this.props.updateStoreValue(this.props.name + '_fileTypeError', error)
    }

    render() {

       
        return (<div className="upload-options">
                <div className="upload-options-top">
                    <h2>
                        Trascina file in quest'area
                    </h2>
                    <div className="barred">
                        <p>
                            oppure
                        </p>
                    </div>
                </div>
                <div className="upload-options-bottom">


                    <ReactFileReader multipleFiles={true}
                                     fileTypes={["image/png", "image/PNG", "image/jpg", "image/JPG", "image/jpeg", "image/JPEG", "application/pdf", "application/PDF", "application/zip"]}
                                     handleFiles={this.handleFiles}
                                     base64={true}>
                        <div className="upload-options-bottom-left">
                            <figure className="doc-right">
                                <img
                                    src={uploadIcon}
                                    alt=''/>
                            </figure>
                            <p className="file-upload-link">
                                Seleziona file
                            </p>
                        </div>
                    </ReactFileReader>

                    
                    <div className="upload-options-bottom-right"
                         onClick={() => this.snapPhoto()}>
                        <figure className="doc-right">
                            <img
                                src={camIcon}
                                alt=''/>
                        </figure>
                        <p className="file-upload-link">
                            Carica foto
                        </p>
                    </div>

                </div>
            </div>

        )
    }
}


const mapStateToProps = state => {
    return {
        activationSteps: state.ProfilationSelectReducer.activationSteps,
        thumbNailInfo:state.ProfilationSelectReducer.thumbNailInfo/*,
        thumbNailImg:state.ProfilationSelectReducer.thumbNailImg*/
    }
};

const mapDispatchToProps = dispatch => ({
    showModal: (modalName) =>
        dispatch(SelectActionCreators.showModal(modalName)),
    showCamModal: (modalName, docId, maxPhotos, step) =>
        dispatch(SelectActionCreators.showCamModal(modalName, docId, maxPhotos, step)),
    updatePropValue: (steps, activeStep) => dispatch(SelectActionCreators.changeValue(steps, activeStep)),
    updateActivation: (index, prop, value) => dispatch(SelectActionCreators.updateActivation(index, prop, value)),
    updateStoreValue: (prop, value) =>
        dispatch(SelectActionCreators.changeProp(prop, value)),
});

/*Profilation.propTypes = {
 steps: PropTypes.array.isRequired,
 activeStep: PropTypes.number.isRequired,
 updatePropValue: PropTypes.func.isRequired
 }*/

export default connect(mapStateToProps, mapDispatchToProps)(FileUploadComponent);