Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload image using ReactJS and save into local storage?

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

like image 609
Akib Avatar asked Sep 04 '17 16:09

Akib


Video Answer


2 Answers

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

like image 148
Sebastien Lorber Avatar answered Sep 21 '22 23:09

Sebastien Lorber


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);
}
like image 39
Angel Cuenca Avatar answered Sep 20 '22 23:09

Angel Cuenca