I tried to overwrite a text file which is in local path through javascript in edge(chromium).
But it doesn’t work.
I want to know that if Edge(Chromium version) supports to create a text file into local path.
If it possible, how can I do that?
We can't overwrite the local text file through JavaScript, it is not secure. If you want to modify the local text file, you could upload it through JavaScript, then, read the text content in the web page, after modifying it, download it to the local path.
Please check the following sample:
<input type="file" id="inputfile" /><br />
<input type="button" id="btn-dwn" value="Download" /><br />
<textarea id="text-val" rows="4"></textarea><br />
<script>
function newFile(data, fileName) {
// download the content to a .txt file.
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//IE11 support
console.log("IE& Edge");
// let blob = new Blob([data], { type: "text/html" });// text/plain;charset=utf-8
let blob = new Blob([data], { type: "text/plain;charset=utf-8" });
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {// other browsers
console.log("Other browsers");
var bl = new Blob([data], { type: "text/plain;charset=utf-8" });
var a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = fileName;
a.hidden = true;
document.body.appendChild(a);
a.click();
}
};
//using FileReader to read the .txt file content
document.getElementById('inputfile').addEventListener('change', function () {
var fr = new FileReader();
fr.onload = function () {
document.getElementById('text-val').value = fr.result;
}
fr.readAsText(this.files[0]);
});
//call the newFile function to download text file.
document.getElementById("btn-dwn").addEventListener('click', function () {
newFile(document.getElementById("text-val").value, "test.txt");
});
</script>
Related
I'm am trying to upload a pdf file, convert it to a BLOB and download again as a pdf file. At the moment I get no errors but when I download the file I get a blank pdf with what looks like a corrupted file name.
I am saving the BLOB in the pdfFile vairable.
<input type="file"
#change="onNewFileUpload($event)">
async onNewFileUpload($event) {
const file = $event.target['files'][0];
const fileReader = new FileReader();
const self = this;
fileReader.onload = function() {
pdfFile = new Blob([fileReader.result], { type: "application/pdf" })
}
fileReader.readAsText(file);
},
<button
#click="downloadPdfFile()"
class="btn btn-success">Download pdfFile</button>
downloadBOBSCertificate() {
const link = document.createElement('a');
// create a blobURI pointing to our Blob
// link.href = pdfFile;
link.href = URL.createObjectURL(pdfFile);
link.download = 'test.pdf';
// some browser needs the anchor to be in the doc
document.body.append(link);
link.click();
link.remove();
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
}
I have an Ionic application which downloads a file from a Web API. The content of the file can be found in the _body property of the HTTP response.
What I'm trying to do is convert this text into an arrayBuffer so I can save the content into a file.
However, the issue that I'm having is that any file (PDF files in my instance) that have images and/or large in size either don't show up at all or show up as correputed files.
At first I thought this was an issue relating Ionic. So to make sure I tried to simulate this issue and I was able to reproduce it.
Is this snippet you can select a PDF file, then download it. You would find that the downloaded file is corrupted and exactly how my Ionic app displays them.
HTML:
<input type="file" id="file_input" class="foo" />
<div id="output_field" class="foo"></div>
JS:
$(document).ready(function(){
$('#file_input').on('change', function(e){
readFile(this.files[0], function(e) {
//manipulate with result...
$('#output_field').text(e.target.result);
try {
var file = new Blob([e.target.result], { type: 'application/pdf;base64' });
var fileURL = window.URL.createObjectURL(file);
var seconds = new Date().getTime() / 1000;
var fileName = "cert" + parseInt(seconds) + ".pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = fileURL;
a.download = fileName;
a.click();
}
catch (err){
$('#output_field').text(err);
}
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
//reader.readAsArrayBuffer(file);
reader.readAsText(file);
}
https://jsfiddle.net/68qeau3h/3/
Now, when using reader.readAsArrayBuffer(file); everything works as expected, however in my particular case, I used reader.readAsText(file); because this is how the data is retrieve for me, this is text form.
When adding these lines of code to try to convert the string into an arrayBuffer
...
var buf = new ArrayBuffer(e.target.result.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=e.target.result.length; i<strLen; i++) {
bufView[i] = e.target.result.charCodeAt(i);
}
var file = new Blob([buf], { type: 'application/pdf' });
...
This will not work and generate PDF files that the browser can't open.
So to recap, what I'm trying to do is somehow convert the result I get from reader.readAsText(file); to what reader.readAsArrayBuffer(file); produces. Because the files I'm working with, or the data im retrieving from my backend is this text form.
In my angular app I get pdf byte and show the file using blob
This is my code
siteService.downloadPdf().then(function (response) {
var file = new Blob([response], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file);
}
else {
var fileURL = URL.createObjectURL(file);
window.location.href = fileURL;
}
});
When I try to download the file I got an error that the file does not saved
This error is when I save the file as is (without the .pdf) and also after adding the .pdf
I am using angular-file saver service https://github.com/alferov/angular-file-saver for downloading files. Download is good but when try to open word document I am getting file is corrupted and word cannot open it and if put my api directly in browser file is good when I open it so I suppose blob is doing something for this issue... For .txt files I am not getting corrupted it is good only for .docx and for .jpeg or .png. Below is my short code for downloading files.
function downloadDocument(fileId, fileName, documentExt) {
var deferred = $q.defer();
var id = encodeURIComponent(fileId);
Restangular.one('download?fileId=' + id).get().then(function(data) {
var file = new Blob([data]);
if (documentExt && documentExt !== 'undefined') {
FileSaver.saveAs(file, fileName + '.' + documentExt);
}
else {
FileSaver.saveAs(file, fileName);
}
});
return deferred.promise;
}
you can use give below code to save your file--
function downloadDocument(fileId, fileName, documentExt) {
var deferred = $q.defer();
var id = encodeURIComponent(fileId);
Restangular.one('download?fileId=' + id).get().then(function(data) {
// try to use data.data or data in blob object
var file = new Blob([data.data], {
type: 'application/octet-binary'
});
var fileUrl = URL.createObjectURL(file);
// for IE 10+
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName+'.'+documentExt);
} else {
var element = document.createElement('a');
element.href = fileUrl;
element.setAttribute('download', fileName+'.'+documentExt);
element.setAttribute('target', '_blank');
document.body.appendChild(element);
element.click();
}
});
return deferred.promise;
}
I'm writing a google chrome extension that uses
chrome.pageCapture.saveAsMHTML(object details, function callback)
function callback (blob mhtmlData) {...};
http://code.google.com/chrome/extensions/dev/pageCapture.html
which basically stores a blob representation of an mhtml page into a variable.
Now I want to let the user download this blob variable as an mhtml file..
I tried this but is gives me a 200kb file filled with random characters.
chrome.pageCapture.saveAsMHTML({tabId: sender.tab.id}, function callback(mhtml){
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onload = function(e) {
window.open(e.target.result);
}
});
Following is some code that I put in a page actions popup. I left the stuff that I didnt use but commented it out for reference.
EDIT:
Using the library from https://github.com/eligrey/FileSaver.js it was easy, maybe you could look at that to see what their doing.
popup.html
<html>
<head>
<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script>
function onLoad(){
var downloadLink = document.querySelector("#MHTML");
var oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
// None of the following worked
//window.open('data:application/octet-stream;'+oFREvent.target.result.slice(5));
//window.open('data:application/message/rfc822;'+oFREvent.target.result.slice(5));
//window.open(oFREvent.target.result);
};
chrome.tabs.getSelected(null, function(tab) {
chrome.pageCapture.saveAsMHTML({tabId: tab.id}, function (mhtml){
/// Works but requires user input
//downloadLink.setAttribute('download',tab.title+'.mhtml');
//downloadLink.setAttribute('href',window.webkitURL.createObjectURL(mhtml));
///Works but awful filename without extension
//window.open(window.webkitURL.createObjectURL(mhtml));
///Doesnt work
//oFReader.readAsDataURL(mhtml);
///Using https://github.com/eligrey/FileSaver.js , works great
saveAs(mhtml, tab.title+'.mhtml');
})
});
}
</script>
</head>
<body onload="onLoad();" style="width: 400px">
<a id="MHTML" href="#">Download Page As MHTML</a>
</body>
</html>
In case you want to give the file a name you could use an anchor element and set the name of the download attribute programmatically:
var reader = new FileReader();
reader.readAsDataURL(mhtml);
reader.onloadend = function(e) {
const dataUrl = e.target.result;
const a = document.createElement('a');
a.href = dataUrl;
a.download = fileName;
a.click();
}