7

Here is my code is like:

<input 
 type="file" 
 id="imageFile" 
 name='imageFile' 
 onChange={this.imageUpload} />

Now I want to store this image in local storage and display it at another side. So I want to store the image in local storage. My code is inside of image upload function.

My function is like:

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

My console print is like C:\fakepath\user-bg.jpg

5
  • stackoverflow.com/questions/19183180/… Commented Sep 4, 2017 at 16:55
  • same used it but error is like ctx.drawImage(img, 0, 0);. Commented Sep 4, 2017 at 16:57
  • ... by local storage you mean a browser's localStorage ? Commented Sep 4, 2017 at 18:00
  • yes I mean local storage for the browser @82Tuskers Commented Sep 5, 2017 at 4:46
  • @Akib then the first link posted by Prakash sharma is something you definitely want to look at. Commented Sep 5, 2017 at 4:53

2 Answers 2

10

First, you should be aware that:

  • LocalStorage can only store strings, so you can store files using a string representation only (like base64)
  • LocalStorage is not really made for storing files, because browsers only offer you limited capacity

If this is really what you want to achieve, here's the solution:

class Hello extends React.Component {

  imageUpload = (e) => {
      const file = e.target.files[0];
      getBase64(file).then(base64 => {
        localStorage["fileBase64"] = base64;
        console.debug("file stored",base64);
      });
  };

  render() {
    return <input 
     type="file" 
     id="imageFile" 
     name='imageFile' 
     onChange={this.imageUpload} />;
  }
}


const getBase64 = (file) => {
  return new Promise((resolve,reject) => {
     const reader = new FileReader();
     reader.onload = () => resolve(reader.result);
     reader.onerror = error => reject(error);
     reader.readAsDataURL(file);
  });
}

JsFiddle

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

1 Comment

Thanks for the code Sebastien, how do I get to convert this back to the image object data ?
1

One implementation to upload files, using Java in the backend and Google App Engine that uses blob Blobstore. First try to call a function in your button that sends the file name:

<input id="btn-chooseImage" className="btn-file"
       onChange={() => this.handleUploadSession()}

After that, call a get function in backend to save the file uploaded and save as a img state to render it.

Js:

handleUploadImg(redirectAction){
     var file = $('#btn-chooseImage')[0].files[0]
     var formData = new FormData();
     formData.append("uploaded_files", file);
     var request = new XMLHttpRequest();
     request.open("POST", redirectAction, true);
     request.send(formData);
     request.onload = function() {
         if (request.status === 200) {
             var response = JSON.parse(request.responseText);
             this.setState({
                 img: '/serve?blob-key=' +response.blobKey.toString()
             });
         }
     }.bind(this);
};

handleUploadSession(){
    var request = new XMLHttpRequest();
    request.open("GET", "/uploadSession");
    request.send();
    request.onload = function () {
        if(request.status === 200){
            var redirectAction = JSON.parse(request.responseText);
            this.handleUploadImg(redirectAction);
        }
    }.bind(this);
}

Java:

@RequestMapping(value = {"/uploadSession"}, method = RequestMethod.GET)
protected void GetUploadSession(HttpServletRequest request,
                                    HttpServletResponse response) throws IOException {

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    String redirectAction = blobstoreService.createUploadUrl("/myView");

    String json = new Gson().toJson(redirectAction);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

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.