3

Hi I have an issue with react. I have a method which after click is starting to import image. Actualy I have onChangeevent with this method on my file input:

fileUploadInputChange(e) {
  console.log(e.target.value); // return url of image like C:\fakepath\pokemon-pikachu-wall-decal.jpg
};

Now I have to convert this uploaded file to blob. How can I do this please?

My other code looks like this:

export class GeneralySettings extends Component {
    /**
     * PropTypes fot component
     * @return {object}
     */
    static get propTypes() {
        return {
            userData: PropTypes.object.isRequired,
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            showAvatarChangeButton: false,
            uploadedImage : '',
        };
        this.inputReference = React.createRef();

    }

    fileUploadAction(){
        this.inputReference.current.click();
    };

    fileUploadInputChange(e){
            console.log(e.target.value);
        };


    /**
     * Render method for user profile
     * @return {*}
     */
    render() {
        return (

                        <div className={'d-flex flex-column mr-2'}>
                            <div className={'position-relative'}
                                 onMouseEnter={() => this.setState({showAvatarChangeButton: true})}
                                 onMouseLeave={() => this.setState({showAvatarChangeButton: false})}>
                                <Avatar name="Foo Bar" className={'position-relative button-cursor'}/>
                                <div
                                    className={`position-absolute ${(this.state.showAvatarChangeButton ? 'd-inlene-block' : 'd-none')}`}
                                    id={'changeAvatarButton'}>
                                    <Button variant={'dark'} size={'sm'} block
                                            onClick={this.fileUploadAction.bind(this)}> Zmeniť</Button>
                                    <input type="file" hidden ref={this.inputReference}
                                           onChange={(e) => this.fileUploadInputChange(e)}/>
                                </div>
            </div>
        );
    }

}

4 Answers 4

11

Here's an example how can you use FileReader.readAsDataURL

const {useState} = React;

const fileToDataUri = (file) => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      resolve(event.target.result)
    };
    reader.readAsDataURL(file);
    })

const App = () => {
  const [dataUri, setDataUri] = useState('')

  const onChange = (file) => {
    
    if(!file) {
      setDataUri('');
      return;
    }

    fileToDataUri(file)
      .then(dataUri => {
        setDataUri(dataUri)
      })
    
  }

  return <div>
  <img width="200" height="200" src={dataUri} alt="avatar"/>
  <input type="file" onChange={(event) => onChange(event.target.files[0] || null)} />
  </div>
}


ReactDOM.render(
    <App/>,
    document.getElementById('root')
  );
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

3

Use FileReader

fileUploadInputChange(e) {
    let reader = new FileReader();
    reader.onload = function(e) {
      this.setState({uploadedImage: e.target.result});
    };
    reader.readAsDataURL(event.target.files[0]);
}

To show/preview image:

<Avatar src={this.state.uploadedImage} name="Foo Bar" className={'position-relative button-cursor'}/>

// or .. for image , use below
<img src={this.state.uploadedImage} alt={""} />

1 Comment

And how can i show this image in my img src ?? Becouse reader.readDataAsUrl not returning anything
1
function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var bb = new Blob([ab]);
    return bb;
}

Comments

0

Select file Method -

    selectFile = () => {
    let uploadfile = document.getElementById('upload_doc');
    if (uploadfile) {
        this.setState({
            selectedUploadFile: uploadfile.files[0],
        });
    }
   };

Upload file and sent as form Data -

 const formData = new FormData();
   formData.append('file', this.state.selectedFile);
   this.uploadFile(formData); // here you can use fetch/Axios to send the form data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.