File Write Operation in javascript - javascript

I need to write into a file in javascript.I tried below Code.I got error like"FileWriter is not defined".please help me in this.
<html>
<head>
</head>
<body>
<input type = "button" value = "write" onclick="WriteFile()">
<script>
function WriteFile()
{
var fileWriter = new FileWriter("C:\Users\ananthi\Desktop\readme.txt");
fileWriter.open() ;
fileWriter.writeLine("Another line") ;
fileWriter.close() ;
}
</script>
</body>
</html>

If you would like to use button call function:
<input type = "button" value = "write" onclick="Download()">
Download () {
let filename = "readme.txt";
let text = "Text of the file goes here.\n1";
let blob = new Blob([text], {type:'text/plain'});
let link = document.createElement("a");
link.download = filename;
//link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}, 100);
}

The File Writer API is defunct and never saw significant browser support.
You cannot write files from browser-based JavaScript. What you do instead is provide the user with a link that they can download, like this:
var filename = "readme.txt";
var text = "Text of the file goes here.";
var blob = new Blob([text], {type:'text/plain'});
var link = document.createElement("a");
link.download = filename;
link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);
That works on browsers that support the File API (which modern ones do, but not IE9 or earlier).

Related

Javascript: How to download csv file from a url

I have a url which has csv file. i want to download that file by JavaScript. during download i will provide file name and by that name file will be download in client pc. i tried below code which is not working. where i made the mistake. please give me hint.
function downloadFile(fileName, urlData) {
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = fileName;
aLink.href = urlData;
aLink.dispatchEvent(evt);
}
downloadFile('Test.csv', 'https://testsite.com/targeting/Export/aa.csv');
Use
aLink.click();
instead of the Dispatch-event
I found code which worked. here is the code which i am following now.
var url = 'https://testsite.com/targeting/Export/aa.csv';
var a = document.createElement("a");
a.href = url;
fileName = url.split("/").pop();
alert(fileName);
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();

HTML Editor with Download Option

I'm looking for a way to add a download feature to my JS that will create a file using the programming that a user might enter in, lets say, a <textarea>. Are there any features in JS that would work similar to this? (HTML Format!!)
var x = document.write("<p>Hi!</p>");
window.replace(x);
And then:
<button onclick="open()">Save</button>
<script>
var hi = document.write("<p>hi</p>;");
open() {
window.open(hi)
}
</script>
After they opened the variable on the new page, the user could use ctrl + s to save the page displayed. Ideas?
Thanks in advance.
<textarea id="text-val" rows="4" style="height: 80%;width: 90%;"></textarea><br/><br/>
<input type="button" id="dwn-btn" value="Save" />
<script>
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function() {
var text = document.getElementById("text-val").value;
var filename = "example.html";
download(filename, text);
}, false);
</script>
I hope this is what you are expecting
Create new Blob from your html script with application/octet-stream mime type. Then use URL.createOjectURL api to generate download link. And navigate to that link. In this example code I navigated using creating temporary link (<a>) element.
function download() {
var blobPart = ['<h1>Test</h1>'];
var blob = new Blob(blobPart, {
type: "application/octet-stream"
});
var urlObj = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.href = urlObj;
a.download = 'filename.html';
a.click();
a.remove();
}
document.getElementById('download-btn').addEventListener('click', download);
Download

Download a PDF file in Javascript

I'd like to download a pdf file with javascript.
The file content will be encoded in base64.
Please help me to investagate why I can't download the pdf file.
index.php:
<?php
$file_content = base64_encode(file_get_contents("1.pdf"));
?>
<!DOCTYPE>
<html>
<head>
<title>Download PDF </title>
</head>
<body>
<div>Hello World!</div>
<input type="button" onclick="download()" value="download"/>
<script>
function download() {
var str = "<?php echo $file_content;?>";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var data = window.atob(str);
var blob = new Blob([data], {type: "application/pdf"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "download.pdf";
a.click();
window.URL.revokeObjectURL(url);
}
</script>
</body>
</html>
Based on this Medium post, here's a solution that uses the base64 string directly:
function download() {
var a = document.createElement("a");
a.style = "display: none";
a.href = "data:application/pdf;base64,<?= $file_content ?>";
a.download = "download.pdf";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Further reading: Data_URIs
download attribute will help you to download the file.
var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
Another possible solution:
If you want to download it using blob content than return response must be declared as arraybuffer
Example:
$http.post('/postmethod',{params}, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
Open the PDF file into new window from where you can save it.

JS download file from the server does not working

I am getting from my server a png file. The response looks like this:
�PNG
IHDR|�<V� IDATx���w�T����ם^����I�
v[$��J��bL����oL�&єob���K��QEQ���RDzoK���˽�?f�Sd��ǃ���s���;�����s�����������������-��#DDDDDDDDDDDD�
When I'm trying to convert it to a blob and download it, the file is empty.
download() {
return this.http.get(url).map(res => this.downloadFile(res.text()));
}
private downloadFile(data) {
const blob = new Blob([data], {type: 'image/png'});
const url = window.URL.createObjectURL(blob);
return url;
}
this.download(this.config.guid).subscribe(url => {
var link = document.createElement("a");
link.href = url;
link.download = "data.png";
document.body.appendChild(link);
link.click();
});
What am I doing wrong?
If you don't need to support IE11, fetch makes it easy to get a Blob for a downloaded resource:
fetch(url).then(response => response.blob()).then(blob => {
// Use the blob here...
const blobUrl = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = blobUrl;
link.download = "data.png";
document.body.appendChild(link);
link.click();
});
That said: I would just make the link an actual link and return the data with the Content-Disposition header set to attachment; filename=data.png. The browser will offer to save the file when the user clicks the link.

How can i create a text file using java script in Unicode encoding?

Unicode Encoding... Gettting UTF-8
I am using this code...
var content = 'demo';
uriContent = "data:application/text," + encodeURIComponent(content);
var link = document.createElement('a');
link.setAttribute('href', uriContent);
link.setAttribute('download', '22ddd' + '.txt');
link.click();
The content in the text file will be in Hindi Language which will be further converted into APS fonts. The font converter software available with the client works when the encoding is Unicode. I am able to download the text file properly but it is in UTF-8 encoding
The documentation says,encodeURIComponent generates only UTF-8. So we must try something different.
I tried to put some pieces together:
a modern browser (Chrome 56) and
a text-econding polyfill
and it works (for me):
<html>
<body>
<script>window.TextEncoder = window.TextDecoder = null;</script>
<script src="encoding-indexes.js"></script>
<script src="encoding.js"></script>
<script>
demo = function() {
var content = 'demo';
var uint8array = new TextEncoder( 'utf-16', { NONSTANDARD_allowLegacyEncoding: true }).encode(content);
var blob = new Blob([uint8array], {type : "octet/stream" });
var url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', '22ddd' + '.txt');
link.click();
};
</script>
<button onClick="demo();">
Test
</button>
</body>
</html>

Categories

Resources