Deleting a file in FileSystem API after read is finished? - javascript

So I'm stuck trying to figure this out.
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function (e) {
var anchor = document.createElement("a");
anchor.setAttribute('href', "data:text/tsv;charset=UTF-8," + encodeURIComponent(this.result));
anchor.setAttribute("download", "log.tsv");
anchor.innerHTML = "Download Log Now";
document.body.appendChild(anchor);
alert("Download by clicking the damn link at the bottom.");
//delete the file?
}
reader.readAsText(file);
});
So my question is how do you delete the file after it's been read? I've tried doing fileEntry.remove(function(){console.log("File Removed.")}); where the comment is but that doesn't work.
Any ideas?

You can have a look on promise-based bro-fs where this is more clean:
fs.init()
.then(() => fs.readFile('file.txt'))
.then(content => console.log(content))
.then(() => fs.unlink('file.txt'))

Related

how to save domtoimage to localstorage

i use dom-to-image javascript package for making div element to png file, i want to save this png file to locastorage and displayed the image on next page how to make it?
i tried localStorage.setItem('testCart', blob) , and the result value is [HTML object blob], i know this is wrong, what should i do?
here is mycode
function onSaveDpn() {
domtoimage.toBlob(document.getElementById("custom-cloth"))
.then(function (blob) {
// code to download file as .png
window.saveAs(blob, "sakaw-custom-depan.png");
// code to save into localstorage
localStorage.setItem( what should I write? )
});
}
Edit, I solved my problem with this
https://www.geeksforgeeks.org/how-to-convert-blob-to-base64-encoding-using-javascript/
this is my new code
function onSaveDpn() {
domtoimage
.toBlob(document.getElementById("custom-cloth"))
.then(function (blob) {
// window.saveAs(blob, "sakaw-custom-depan.png");
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
var base64String = reader.result;
localStorage.setItem("scart", base64String);
};
});
}
I hope this can help you guys

fileReader.onload does not run second time, even after selecting different file

document.getElementById("uploadExcel").addEventListener("click", function () {
$("#uploadExcel").attr('disabled', true);
$('#loader').show();
if (selectedFile) {
var fileReader = new FileReader();
alert("2");
fileReader.onload = function (event) {
alert(event);
var data = event.target.result;
alert("3");
var workbook = XLSX.read(data, {
type: "binary", cellDates: true, dateNF: 'mm/dd/yyyy;#'
});
alert("4");
workbook.SheetNames.forEach(sheet => {
alert("5");
let rowObject = XLSX.utils.sheet_to_row_object_array(
workbook.Sheets[sheet]
);
let jsonObject = JSON.stringify(rowObject);
alert("Get Data");
getData(jsonObject);
//document.getElementById("jsonData").innerHTML = jsonObject;
});
};
alert("6");
fileReader.readAsBinaryString(selectedFile);
} else {
alert("error");
}
});
Now let me explain what is happening:
The page loads and I select the file to upload, it goes through even if it has excel errors, it will take the file and read it, convert it and throw errors.
So then I change that excel file to be error-free and try to click the upload button again, but this time the code enters the above function, and it won't go past fileReader.onload = function (event) it alerts "2" and then stops working.
Can you please tell me why is this happening and how to avoid this without a page reload, because if I do a page reload everything works as expected.
Thanks

Adding a watermark to a image before uploading with watermarkjs

I'm trying to add a watermark to a image with watermark.js before it get uploaded but, I can't quite figure out how to do it.
With the code i got underneath the upload part of the uploadFile function is working but, the image data gets lost within the watermark script somehow and the uploaded image on AWS S3 is just a small transparent square.
I've also added my function to preview the image, and this is working fine and displays the image with the watermark as it is supposed to.
So why is one of the functions working while the other have problems, what am I doing wrong in the uploadFile function?
const uploadFile = file => {
axios.get(`/api/imageUpload/${file.type}`)
.then(uploadConfig => {
watermark([file, '../static/images/watermark_white.png'])
.image(watermark.image.lowerRight())
.then(img => {
axios.put(uploadConfig.data.url, img, {
headers: {
"Content-Type": file.type
},
}).then(() => {
props.onUpload(uploadConfig.data.key);
});
});
});
};
const previewFile = file => {
if (!isImage(file)) {
return;
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
let img = document.createElement("img");
img.src = reader.result;
watermark([img, '../static/images/watermark_white.png'])
.image(watermark.image.lowerRight())
.then(function (img) {
document.getElementById("gallery").appendChild(img);
});
};
};
Turns out I only had to change .image(watermark.image.lowerRight()) to .blob(watermark.image.lowerRight()) and everything works.

pass input file to background script

I want to pass the input file from content page to extension background script, and then load it with FileReader() in the extension background script.
So in the web page I have a <input type="file"> and from onchange event I pass the file from content script to background page like this:
var myfile = document.getElementById('fileid').files[0];
chrome.runtime.sendMessage({myevent: "start", inputfile: myfile}, function(response) {});
in the background script I have this:
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.myevent==="start")
{
var reader = new FileReader();
reader.onload = function(e) {
// file is loaded
}
reader.readAsArrayBuffer(message.inputfile);
}
});
but FileReader not load it, I'm not sure if this is correct way , but all i need is to pass the input file element to background script and load it with FileReader to send it with HTTP POST from background script. Please tell me what is wrong or how to do it correctly. It will help a lot if I see a sample code, because I'm new to chrome extension development, and not so experienced.
All messages send through the Chrome extension messaging API MUST be JSON-serializable.
If you want to get the contents of a file at the background page, you'd better create a (temporary) URL for the File object, pass this URL to the background page and use XMLHttpRequest to grab its contents:
// Create URL
var url = URL.createObjectURL(myfile);
// Pass URL to background page (ommited for brevity) and load it..
var x = new XMLHttpRequest();
x.onload = function() {
var result = x.response;
// TODO: Use [object ArrayBuffer]
};
x.open('GET', url); // <-- blob:-url created in content script
x.responseType = 'arraybuffer';
x.send();
Though why do you want to send the file to the background page? Content scripts can also send cross-origin requests.
This works for chrome. You could find the whole production code here.
https://github.com/Leslie-Wong-H/BoostPic/tree/7513b3b8d67fc6f57718dc8b9ff1d5646ad03c75/BoostPic_Chrome/js
main.js:
// Crossbrowser support for URL
const URLObj = window.URL || webkitURL;
// Creates a DOMString containing a URL representing the object given in the parameter
// namely the original Blob
const blobUrl = URLObj.createObjectURL(imageBlob);
console.log(blobUrl);
chrome.runtime.sendMessage(blobUrl, (res) => {
imgUrl = res;
console.log(imgUrl);
clearInterval(refreshIntervalId);
// To prevent that it happens to halt at " Image uploading ..."
setTimeout(() => {
var imgUrlText = document.querySelector(imgUrlTextBoxId);
imgUrlText.value = imgUrl;
}, 1000);
// double check to clear interval to prevent infinite error loop of LoadingStateOne
// Hope it works.
setTimeout(() => {
clearInterval(refreshIntervalId);
}, 500);
console.log("Stop uploading state message");
background.js:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.startsWith("blob")) {
console.log("RECEIVED");
getBase64Url(request).then((res) => {
console.log("Arrived here");
// Acquired from https://stackoverflow.com/questions/18650168/convert-blob-to-base64/18650249#
const reader = new FileReader();
reader.readAsDataURL(res);
reader.onloadend = function () {
const base64data = reader.result;
console.log(base64data);

FileReader isn't working?

this is frustrating. I've been running this code in Safari, Firefox and Chrome - all latest versions - and it doesn't work. Is it working for anyone else? I'm getting my file reference from <input type='file' id='file' name='file'>
console.log("Have now created a new file reader and it looks like this..." + reader);
reader.onload = function() {
var contents = event.target.result;
console.log("File contents: " + contents );
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
}, false);
What am i doing wrong?
Thanks,
J.Wells
What am i doing wrong?
You seem to have forgotten the event parameter of the onload handler. Instead of using event.target, you also might just use reader.
Also, in the fiddle you are creating the FileReader in a very odd way. You might want to read the introduction Using files from web applications at MDN.
document.getElementById("file").addEventListener("change", function(e) {
var file = e.target.files[0],
reader = new FileReader();
console.log("Have now created a new file reader and it looks like this..." + reader);
reader.onload = function(event) {
// ^^^^^
var contents = event.target.result;
console.log("File contents: " + contents );
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
}, false);

Categories