javascript file download - javascript

I need to download a file (test.xml) and allow/prompt user to save the file on click on download button. The file resides in url "http://localhost/test/test.xml" .
I have added html code
<input type=button value="Download" onclick='javascript:download()/>
and javascript code is
function download() {
var url = "http://localhost/test/test.xml";
window.open(url, 'Download');
}
But this opens the page in new window. How do I prompt to download and save the file. Any inputs will be of help. Thanks

You have to change the content type in the header. You need to do some server scripting or configurate your webserver.
I Googled a link that will help you in the right direction: http://www.boutell.com/newfaq/creating/forcedownload.html

Using you inital code, if you have access to the backend, when the xml is requested, add the following header with it:
Content-disposition: attachment; filename=test.xml;
Another route would be to use xmlhttprequest to get the file, then use a flash plugin to save it. I've used this method a bit, and the flash swf can be found here

set the content type for the response header of the xml to be application/xml

html:
<input id="downloadthis" value="Download"/>
inside javascript tag:
$('#downloadthis').click( function() {
window.location.href = 'http://localhost/test/test.xml';
} );
REF: https://stackoverflow.com/a/4864264/405117

Related

JavaScript - How to download image from fetched in network [duplicate]

This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines. I'm thinking this should be an easy one to answer.
I want a simple file download, that would do the same as this:
Download!
But I want to use an HTML button, e.g. either of these:
<input type="button" value="Download!">
<button>Download!</button>
Likewise, is it possible to trigger a simple download via JavaScript?
$("#fileRequest").click(function(){ /* code to download? */ });
I'm definitely not looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.
You can trigger a download with the HTML5 download attribute.
Download
Where:
path_to_file is a path that resolves to an URL on the same origin. That means the page and the file must share the same domain, subdomain, protocol (HTTP vs. HTTPS), and port (if specified). Exceptions are blob: and data: (which always work), and file: (which never works).
proposed_file_name is the filename to save to. If it is blank, the browser defaults to the file's name.
Documentation: MDN, HTML Standard on downloading, HTML Standard on download, CanIUse
For the button you can do
<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>
HTML:
<button type="submit" onclick="window.open('file.doc')">Download!</button>
A simple JS solution:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
With jQuery:
$("#fileRequest").click(function() {
// hope the server sets Content-Disposition: attachment!
window.location = 'file.doc';
});
You can do it with "trick" with invisible iframe. When you set "src" to it, browser reacts as if you would click a link with the same "href". As opposite to solution with form, it enables you to embed additional logic, for example activating download after timeout, when some conditions are met etc.
It is also very silient, there's no blinking new window/tab like when using window.open.
HTML:
<iframe id="invisible" style="display:none;"></iframe>
Javascript:
function download() {
var iframe = document.getElementById('invisible');
iframe.src = "file.doc";
}
Bootstrap Version
<a class="btn btn-danger" role="button" href="path_to_file"
download="proposed_file_name">
Download
</a>
Documented in Bootstrap 4 docs, and works in Bootstrap 3 as well.
I think this is the solution you were looking for
<button type="submit" onclick="window.location.href='file.doc'">Download!</button>
I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.
downloadCSV: function(data){
var MIME_TYPE = "text/csv";
var blob = new Blob([data], {type: MIME_TYPE});
window.location.href = window.URL.createObjectURL(blob);
}
You can hide the download link and make the button click it.
<button onclick="document.getElementById('link').click()">Download!</button>
<a id="link" href="file.doc" download hidden></a>
What about:
<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">
In my testing the following works for all file types and browsers as long as you use a relative link:
<button>Download 2</button>
/assets/hello.txt is just a relative path on my site. Change it to your own relative path.
my_file.txt is the name you want the file to be called when it is downloaded.
Explanation
I noticed there were comments under a lot of the answers that said the browser would just try to open the file itself rather than downloading it depending on the file type. I discovered this to be true.
I made two buttons to test it out using two different methods:
<button onclick="window.location.href='/assets/hello.txt';">Download 1</button>
<button>Download 2</button>
Notes:
Button 1 opened the text file in a new browser tab. However, Button 1 would download the file for file types that it couldn't open itself (for example, .apk files).
Button 2 downloaded the text file. However, Button 2 only downloaded the file if the path was relative. When I changed the path to an absolute path, then the browser opened it in a new tab.
I tested this on Firefox, Safari, and Chrome.
Hello I just include the word 'download' and works well.
<a href="file.pdf" download>Download</a>
So in javascript you can use the follow:
function onStartedDownload(id) {
console.log(`Started downloading: ${id}`);
}
function onFailed(error) {
console.log(`Download failed: ${error}`);
}
var downloadUrl = "https://example.org/image.png";
var downloading = browser.downloads.download({
url : downloadUrl,
filename : 'my-image-again.png',
conflictAction : 'uniquify'
});
downloading.then(onStartedDownload, onFailed);
If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.
const download = document.getElementById("fileRequest");
download.addEventListener('click', request);
function request() {
window.location = 'document.docx';
}
.dwnld-cta {
border-radius: 15px 15px;
width: 100px;
line-height: 22px
}
<h1>Download File</h1>
<button id="fileRequest" class="dwnld-cta">Download</button>
<button>Download!</button>
This will download the file as .doc file extension is not supported to be opened in browser.
One of the simplest way for button and the text-decoration will help to alter or to remove the text decoration of the link.
Anywhere between your <body> and </body> tags, put in a button using the below code:
<button>
<a href="file.doc" download>Click to Download!</a>
</button>
This is sure to work!
all you need to do is add Download after the file name which you have entered:
Before:
Download!
After
<a href="file.doc" Download >Download!</a>
Make sure the download is written with a capital letter otherwise it's not gonna work.
This is what finally worked for me since the file to be downloaded was determined when the page is loaded.
JS to update the form's action attribute:
function setFormAction() {
document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
}
Calling JS to update the form's action attribute:
<body onLoad="setFormAction();">
Form tag with the submit button:
<form method="get" id="myDownloadButtonForm" action="">
Click to open document:
<button type="submit">Open Document</button>
</form>
The following did NOT work:
<form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">
If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:
<div onClick=(()=>{downloadjs(url, filename)})/>
*it's jsx/react syntax, but can be used in pure html
Not really an answer to the original question but it may help others which face similar situations as myself.
If the file you want to download is not hosted on the same origin but you want to be able to download it, you can do that with the Content-Disposition header. Make sure the server includes the header when responding to requests of the file.
Setting a value like
Content-Disposition: attachment will ensure that the file will be downloaded instead of viewed in the browser.
A simple Download pointing to your file should download it in this case.
If you want
Download
for the ability to download files that would be rendered by the browser otherwise, But still want a neat javascript function to use in a button; you can have an invisible link in html and click it in javascript.
function download_file() {
document.getElementById("my_download").click()
}
<a id="my_download" href="path_to_file" download="file_name" style="display:none;"></a>
<button onClick="download_file()">Download!!!</button>
Another way of doing in case you have a complex URL such as file.doc?foo=bar&jon=doe is to add hidden field inside the form
<form method="get" action="file.doc">
<input type="hidden" name="foo" value="bar" />
<input type="hidden" name="john" value="doe" />
<button type="submit">Download Now</button>
</form>
inspired on #Cfreak answer which is not complete
The solution I have come up with is that you can use download attribute in anchor tag but it will only work if your html file is on the server. but you may have a question like while designing a simple html page how can we check that for that you can use VS code live server or bracket live server and you will see your download attribute will work but if you will try to open it simply by just double clicking html page it open the file instead of downloading it.
conclusion: attribute download in anchor tag only works if your html file is no server.
For me ading button instead of anchor text works really well.
<button>Download!</button>
It might not be ok by most rules, but it looks pretty good.
If you use the <a> tag, do not forget to use the entire url which leads to the file -- i.e.:
Download

Jquery $.post html to external php and print the html as pdf. Need to find optimal solution

I get mysql data.
Create - echo the mysql data as html.
If visitor wants to print the data as pdf (i mean to create pdf file and save on computer), i with jquery take the data and send to external php file. In the external php file, using http://www.tcpdf.org solution i want to create pdf file (on fly, only as variable; i do not want to save the file on my server) so that user can save it.
User remains on the same url, just after user clicks button, i offer the user to save rendered pdf. I do not want to change url or add html content to the url (like print_pdf.php?html_content).
At the moment i use code like below.
<div id="to_print_as_pdf">
<div>Some content from mysql</div>
<table>Another content from mysql</table>
</div>
<button type="button">Click to print as pdf</button>
<span id="result_print_pdf"></span>
Jquery to send the data
<script>
$("button").click(function(){
$.post('_prepare_to_print_pdf.php',
{ content_to_print: $('#to_print_as_pdf').html() },
function(result_print_pdf) {
$('#result_print_pdf').html(result_print_pdf).css('color', 'black');
});
});
</script>
File _prepare_to_print_pdf.php
$_SESSION['content_to_print'] = trim($_POST['content_to_print']);
<script>
window.location.href = "https://www.example.com/_print_pdf.php";
</script>
File _print_pdf.php
//Use http://www.tcpdf.org solution
$html = $_SESSION['content_to_print'];
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output('example_001.pdf', 'I');
How to do the same without _prepare_to_print_pdf.php? Above solution waste server resources (creating session).
I tried with $.post to send html content directly to _print_pdf.php, but in such case instead of prompting to to save pdf file, i see "garbage" characters...
Solution at the moment
May be will help to someone
$('#for_hidden_form_for_print_pdf').append('<form action="_print_pdf.php" method="post" target="_blank" id="hidden_form_for_print_pdf">' +
'<textarea id="content_to_print" name="content_to_print">html content to send </textarea>' +
'<div><button style="display: none;" id="btn_to_print_pdf">Print pdf</button></div></form>');
$('#btn_to_print_pdf').trigger('click');
$( "#hidden_form_for_print_pdf" ).remove();
So when visitor clicks button/icon, i take necessary html data, insert into textarea id="content_to_print". Then trigger click for btn_to_print_pdf, then remove appended form. So i send to external php file, necessary html code. In php file i process the html code, create content for pdf file and print.

Javascript to print my pdf file

In my tomcat webapps folder contain one PDF I need to button press to new window show the file and print option open using JavaScript Is possible or any other way?
function print() {
var file = window.open('http://url/to/pdf');
file.print();
}
<input type="button" value="Print" onclick=print()>
I believe this is possible. Determine the url of the pdf on the tomcat web container and then the following JavaScript should work:
var pdfWin = window.open('MyPDF.pdf', '_blank', 'fullscreen=yes');
pdfWin.focus();
pdfWin.print();

open file using jQuery

I try to open a file using jQuery. Here is my HTML,
<button onclick='load();'>load</button>
Here is my js code:
function load() {
var fileSelector = $('<input id="load" type = "file" multiple />');
fileSelector.click();
//code here to get the files ...
}
Now I want to get the loaded files, what should I do?
The HTML5 File Api (http://dev.w3.org/2006/webapi/FileAPI/) allows opening files, however the files must be selected by the User for security.
If you need to open a file without user interaction, then it is necessary to do this on the server side with a language like PHP for example.
Here's my solution
I used the file type input and then use the Jquery trigger function to trigger the click event for file input.
$(function(){
$("#btnFile").click(function(){
$("#file").trigger("click");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="file" type="file" hidden/>
<button id="btnFile">Click Me</button>
You can open JSON file with JavaScript and use fetch('json_file patch') .

Simplest way for image upload function , without refreshing page

Here's a challenge:
I don't care about which language to use, Javascript, PHP, .. whatever.
I need the most simple way to let my user upload an image.
I will later offer the user a way to place it on a canvas (displayed inside a div, with jquery draggable)
I can not have the page refreshed since there are useful variables in other fields etc..
(I don't have any security preferences as this will be a local website for intranet)
I tried:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
</br>
<input type="file" name="file" id="file" size="70%"><br>
</br>
<input type="submit" name="submit" value="Submit">
</form>
But then came to realise there are soo many options out there, such as uploadify, and i easily got lost online..
You have two choices to make a file upload w/o refreshing the page:
Use HTML5 form upload
Post the form to an hidden iframe
The latter one gives best browser compatibility, and is what I'd suggest you to use. To post to an hidden iframe, simply set the target of the form to the iframe:
<script>
// Global callback function from the file
function uploadCallback(){
console.log("File is uploaded!");
}
</script>
<iframe name="hiddentarget" style="display:none;"></iframe>
<form action="upload_file.php" method="post" enctype="multipart/form-data" target="hiddentarget">
...
To respond back to the site from the iframe, you will have to go through the window.top frame as such:
upload_file.php:
<?php
// Uploading stuff
// ...
// "Talk" back to the site
// Of course you can (should) pass some parameter to this JS-function, like the filename of the recently uploaded image.
echo "<script>window.top.uploadCallback();</script>";
?>
EDIT:
As suggested by other users; the optimal solution would be to use the File API where supported, and fall back to the hidden iframe on browser that doesn't support it. This gives you nice features such as file uploda progress for example.
The way that I would suggest is using AJAX and and make your upload box a div which can be replaced when the upload is successful. Instead of traditional post you then create a Javascript function for onSubmit. Your action can then be changed to #.
If you lookup AJAX there are some great tutorials about and you will be able to do many more amazing things.
Alternatively look into jQuery which will definitely have something to help you
I'm gonna show you an example on how to use the jQuery Form Plugin to upload files to your server really easy without needing to refresh the page.
First off, download and install the jQuery Form Plugin. After you do that, include it in your files where you want to make use of it. Add an ID attribute to your form tag like this:
id="unique_id"
After you have identified the upload form, put this code in your jQuery:
$(function() {
$('#unique_id').ajaxForm({
target: '.myTarget' // Display here whatever the server side script returns
success: function(response) {
// An usual success callback
}
})
})
Assuming that your server side language is PHP, this is how a simple upload script would look like (upload_file.php):
<?php
$uploaddir = 'your_upload_dir/something';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']); // Filename
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo $uploadfile;
} else {
echo "Error";
}
?>
Where userfile is the name attribute of your file input (<input type="file" />).
The above code combined returns the relative path to your image which you can use to display the image inside an img tag. You must use Javascript (or jQuery) for that.

Categories