Young L.
Young L.

Reputation: 1042

How to load image and convert to blob in react

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

}

Upvotes: 3

Views: 54033

Answers (4)

freedomHongKong
freedomHongKong

Reputation: 101

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

Upvotes: 1

gdh
gdh

Reputation: 13702

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={""} />

Upvotes: 3

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11305

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>

Upvotes: 11

Dlucidone
Dlucidone

Reputation: 1101

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

Upvotes: 0

Related Questions