How to read or convert an image blob url into an i

2019-09-01 18:29发布

问题:

I have an image that is stored in local storage. On load the image is displayed.

componentDidMount() {
 const reader = new FileReader();
 reader.onload = e => {
  this.setState({ blob: e.target.result });
 };
 reader.readAsDataURL(this.props.file);
}
render() {
 return (
  <div>
   <img src={this.state.blob} />
  </div>
 )
}

The file object looks like this:

lastModified:1535424554987
name:"test.jpeg"
preview:"blob:http://localhost:8080/b52098ca-087f83c778f0"
size:41698
type:"image/jpeg"
webkitRelativePath:""

When I refresh the page and try to load the preview again, it doesn't display the image, and the file object looks different:

{preview: "blob:http://localhost:8080/b52098ca-087f83c778f0"}

Is it possible to read the image from this url? Or is it impossible to render the image without the full file object?

回答1:

blob URL is temporary. if you reload the web page, the blob URL will gone.
If you want to save the image in localStorage you can save it as base64 data.

But if your image is too big localStorage won't suit because it has limits which depend on the browser from 5MB to 10MB.



回答2:

It's impossible as far as i'm aware to save files to/from localStorage this is because it runs JSON.stringify over the data.