0

I am using URL.createObjectURL() to convert image to blob URL and saving it to database. Now i want to call that URL and convert it back to Image and display it

Converting to URL

  onImageChange = event => {
if (event.target.files && event.target.files[0]) {
  let img = event.target.files[0];
  this.setState({
    image: URL.createObjectURL(img)
  });
  console.log(this.state.image);
}


};

calling the file

            <td className="text-left">{offers.offertitle}</td>
            <td className="text-left">{offers.offerdescription}</td>
            <td className="text-left"><img src={offers.offerimg} /></td>

saving the URL to DB

  onSubmit = e => {
e.preventDefault()

addItem({offertitle: this.state.offertitle, offerdescription: this.state.offerdescription,offerimg: this.state.image ,vid: this.state.vid}).then(() => {
  this.getAll()
  toastr.success('Offer Added Succesfully', 'Uni Perks', { timeOut: 800 })
  setTimeout(() => {
    window.location.reload();
  }, 1000);

})
this.setState({
  offertitle: '',
  offerdescription:'',

})
  }
  • do you see this one: https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript ? – Pavel Petrovich Jun 16 '20 at 20:52
  • I am new to react js I dont understand it can you please help me do it – Faraz Azhar Jun 16 '20 at 21:00
  • You don't need to convert image back. Just set image attribute `src` equals to your base64 image. – Pavel Petrovich Jun 16 '20 at 21:13
  • i dont get it what is base64? – Faraz Azhar Jun 16 '20 at 21:33
  • My mistake. `URL.createObjectURL` doesn't create base64 representation of image. It creates a `DOMString` containing a URL representing the object given in the parameter. But your `img` it's - `DOMString` and you need just set `src` attribute equals to your `DOMString`. See this example: https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications#Example_Using_object_URLs_to_display_images – Pavel Petrovich Jun 17 '20 at 08:21
  • Saving an object url in a database is not useful as the url is only valid for the session that it was created in. You have to save the image data or a url that persists. – Musa Jun 17 '20 at 14:18

0 Answers0