Downloading file using javascript not working in Mozilla - javascript

This how my code works.
When I clicked the button, it will download the file.
My code is working in Google Chrome but not working in Mozilla Firefox.
Here are my codes
HTML
<button type='Button' onClick='dlpdf("http://www.energy.umich.edu/sites/default/files/pdf-sample.pdf")'>Download</button>
JAVASCRIPT
function dlpdf(fileURL){
if (!window.ActiveXObject) {
var save = document.createElement('a');
//alert(fileURL);
save.href = fileURL;
save.target = '_blank';
save.download = fileURL || 'unknown';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
}

Related

Ajax file download over GET not working in Opera

This code works in all major browsers excpet in latest Opera 71 (Windows).
The behaviour is that no error or info shows up but the download never starts from end user perspective. In developer tools I see the binary content of the example pdf document in response tab.
It seems that the dynamic creation of tags is not working.
function downloadFile(urlToSend) {
var req = new XMLHttpRequest();
req.open("GET", urlToSend, true);
req.responseType = "blob";
req.onload = function (event) {
var URL = window.URL || window.webkitURL;
var contentType = req.getResponseHeader('content-type');
var blob = new Blob([req.response], {type: contentType});
var downloadUrl = URL.createObjectURL(blob);
var contentDisposition = req.getResponseHeader('content-disposition');
//var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
var filename = 'doku.pdf'; //contentDisposition.match(/filename*="(.+)"/)[1];
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
//code which gets executed by Opera
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
};
req.send();
}

Trigger click n a element created in javascript and download csv file

I'm trying to create an a element and trigger click event on it and down load a csv file on ajax response( the data array its for test purposes only)
$(document).on('click','.csv',function(){
var ticketid = $(this).attr('data-ticket');
$.ajax({
url: window.location.href,
method:'POST',
data: {
action:"export-csv",
ticketid: ticketid
},
}).done(function(response){
var data = [
['Foo', 'programmer'],
['Bar', 'bus driver'],
['Moo', 'Reindeer Hunter']
];
var response_object = $.parseJSON(response.html);
var result = toArray(response_object);
var csv = 'Name,Title\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log( encodeURI(csv));
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'data.csv';
hiddenElement.click();
});
});
With this code there is no error but there is not download too.
Don't use trigger() on DOM object since it's a jQuery method, just .click() should do the work, Check the working example below :
hiddenElement.click();
Hope this helps.
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8, ABCD';
hiddenElement.download = 'aaa.csv';
hiddenElement.click();
Plain javascript doesn't have a trigger() method, only jQuery does.
To trigger a click you'd just do
hiddenElement.click();
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI('John,2018,House,312,3.75');
hiddenElement.download = 'aaa.csv';
hiddenElement.click();
This does require a browser that supports the download attribute
Triggering the click event of a link in via JS does not work - at least in Firefox (probably some kind of "security" restriction?). You'll have to create your own event and fire that:
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI('foo,bar,baz,42');
hiddenElement.download = 'aaa.csv';
hiddenElement.click();
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, false);
hiddenElement.dispatchEvent(event, true);
Depending on which browsers you need to support, you might have to do a feature detection for older browsers (IE), checking for document.createEventObject, then using hiddenElement.fireEvent('onclick').
You Must Use SetAttribute Method :
<script>
var hiddenElement = document.createElement('a');
hiddenElement.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURI(csv));
hiddenElement.setAttribute("download", 'aaa.csv');
hiddenElement.setAttribute("click", "DownloadFile(this)");
function DownloadFile(e) {
// Do Logic code here ..
}
</script>

How to download PDF automatically using js?

My scenario is that PDF file download automatically, then user fills it and when click on submit button in PDF it connect to java servlet and save it in DB.
User click on Button
JavaScript code run and PDF file download automatically
open file using JavaScript automatically
user fills & press submit
after submit servlet code run and save data in db
In my Application just the 2nd point is missing. Please provide code how to interact with extension using JavaScript to download file automatically.
I just want to download the file.
Use the download attribute.
var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
save.download = fileName || filename;
if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
document.location = save.href;
// window event not working here
}else{
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
How to use?
download_file(fileURL, fileName); //call function
Please try this
(function ($) {
$(document).ready(function(){
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if($('.submitclass').length){
$('.submitclass').click(function(){
$email_id = $('.custom-email-field').val();
if (validateEmail($email_id)) {
var url= $(this).attr('pdf_url');
var link = document.createElement('a');
link.href = url;
link.download = url.split("/").pop();
link.dispatchEvent(new MouseEvent('click'));
}
});
}
});
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<div class="form-item form-type-textfield form-item-email-id form-group">
<input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
</div>
<button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
Or use download attribute to tag in HTML5
for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf
e.g. you're using php and $filepath contains pdf file path.
so you can write javascript like to to emulate download dialog box.
<script language="javascript">
window.location.href = '<?php echo $filepath; ?>';
</script
Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.

Not able to create .txt file using Chrome

I am a novice to javascript trying to create a .txt file from an .htm document on my PC.
The following code works well with IE, and creates a file (say "A1.txt") on my desktop. However, I can not able to create the file using Chrome. I am running Windows Vista.
Let me know what modification I need to carry out to run this code using Chrome.
Thanks in advance
<html>
<head>
<script type="text/javascript" language="javascript">
</script></head>
<body>
<form name="F1">PN<input type="text" name="T1"></form>
<p><input type="button" value="Submit" onclick="dp()"></p>
</body></html>
<script>
myObject = new ActiveXObject("WScript.Shell");
function dp()
{T1 = "";
var txtfile = "A"+document.F1.T1.value+".txt";
var fso = new ActiveXObject("Scripting.FileSystemObject");
var myFile = fso.OpenTextFile(txtfile,8, true,0);
myFile.write("Test");
myFile.Close();
fso = null;
}
</script>
Please help.
Use the HTML5 File API
function dp() {
if ('Blob' in window) {
var fileName = "A" + document.F1.T1.value;
var textToWrite = "Test";
var textFileAsBlob = new Blob([textToWrite], {
type: 'text/plain'
});
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.innerHTML = "Download File";
if ('webkitURL' in window) {
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
} else {
alert('Your browser does not support the HTML5 Blob.');
}
}
JSFiddle
See more detailed sample here.

Download file from http url by JQuery Ajax

I have on html page input type text. I want paste URL, on example http://www.quicksprout.com/images/foggygoldengatebridge.jpg in this text field and click button "download" and download this file to my computer.
I want want to realize this with AJAX. Maybe do you know some AJAX plugins or code that could realize downloading file from HTTP URL?
First MEthod
function SaveToDisk(fileURL, fileName) {
//alert("yes i m working");
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
Second MEthod
function downloadme(x,y){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null',y);
myTempWindow.close();
}
You don't need AJAX to do that, nor would you be able to because of CORS limitations. Instead try something like this.
HTML:
<input type="text" placeholder="URL" id="url"/>
<input type="text" placeholder="Filename" id="name"/>
<a id="download">Download Link</a>
JavaScript:
var url = document.getElementById('url'),
name = document.getElementById('name'),
a = document.getElementById('download');
a.addEventListener('click', function () {
this.setAttribute('src', url.value);
this.setAttribute('download', name.value);
});

Categories