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
First, you should be aware that:
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With