How to download a local file with javascript function - javascript

What is the best and fastest way to download a local file with javascript function:
I have a button once clicked should launch the download process, I am trying to use javacript to handle this but it is not working !!!!
here is the code: the function receives the file name as parameter and the path is static:
function downloadFile(filename) {
var filePath = "C:\\LangsDirectory\\Test\\" + filename;
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = filePath;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}

The download attribute does not work on cross-origin URLs and all file: scheme URLs are considered cross-origin.
The only way I can see to do this would be to use a file <input> to have the user select the file, then read it with JavaScript, generate a Blob from it, and then set up a download for that.
I wouldn't bother. The file is already local. The user can move or copy it to wherever they like using their normal file manager.

Related

javascript - make browser send PDF file to download folder

How do I send a PDF file I am downloading from a server to the browser's download area instead of opening it in a browser window?
I am working with C# in Blazor. This is my current code, which I need to modify, but don't know how to (ofc I googled before asking here):
async void DownloadDocument(string apiURL, Guid ID)
{
JSRuntime.InvokeAsync<string>("open", $"{apiURL}/GetPDF/{ID}", "_blank");
}
The server returns a FileStreamResult here and the browser shows the file in a new tab. I want it to send it to its downloads folder instead.
You are invoking a JS Function called "open" with two params. (https://developer.mozilla.org/en-US/docs/Web/API/Window/open)
Try creating your own JS download function inside of a script file / tag and invoking it.
The crucial part to save a file in the downloads folder is to set the download attribute of the a tag.
It could look something like this.
inside wwwroot/index.html:
<script>
window.downloadFile = (fileName, pdfData) => {
const linkSource = `data:application/pdf;base64,${pdfData}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
downloadLink.remove();
}
</script>
and in your blazor component:
async void DownloadDocument(string apiURL, Guid ID)
{
// call your api to download the file you want to download
var response = await Http.GetAsync($"{apiURL}/GetPDF/{ID}"));
// convert to base64
var pdfExportBytes = await response.Content.ReadAsByteArrayAsync();
var pdfExportB64 = Convert.ToBase64String(pdfExportBytes);
// invoke js download
await JSRuntime.InvokeVoidAsync("downloadFile", "FileName", pdfExportB64);
}
The file will still be opened if configured so in the users browser, but it will also be stored in the download folder.

Javascript download: detect rename of file

If I use some code like this, to start a Download with Javascript in my browser:
const link = document.createElement("a");
link.style.display = "none";
link.href = URL.createObjectURL(file);
link.download = file.name;
document.body.appendChild(link);
link.click();
Do I have any way to understand if the file has been renamed during download? I mean: if I download two times the file test.txt, the second one is renamed in something like test(1).txt.
Any chance to detect this change in the script?
Thanks!
No.
There is no API that would provide that information.
Renaming gets done by the browser automatically if there already is a file with the same name. Therefore no.
These no way to detect the filename change.
if u want avoid the duplicated download (file name duplicated) from the same page as alternative solution u can create on an array to store previous filename

Download PDF from url react

I have a publicly accessible url to a PDF in Google Cloud Storage. I want to be able to create a button/link in react which allows users to download this PDF to their own computer. I'm wondering what is the best approach to do this and which libraries would be of help? Is there any documentation on this? Thanks
In order to force download a file, you have a number of options. First, the easiest is using the download attribute of an anchor tag:
PDF
However, this is not supported on IE and a number of other browsers in their earlier versions. But the maximum impact of this is it will open in a new tab which in my opinion is graceful degradation. See the full list of supported versions.
If this is not enough, you have to make some changes server-side. You can configure a server in many ways, but as an example, a .htaccess file can have the following:
<Files *.pdf>
Header set Content-Disposition attachment
</Files>
You can dynamically generate a link or button. Snippet bellow:
var sampleBytes = new Int8Array(4096); // In your case it should be your file
var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "octet/stream"}), // or application/pdf
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());
saveByteArray([sampleBytes], 'example.txt'); // You can define the filename

send file from server to client on bokeh

I have made a user interface to fetch data from a MySQL table and visualize it. It is running on a bokeh server. My users connect remotely to the server using their browser (firefox). This works perfectly fine: I simply import the table into a pandas dataframe.
My users also need to download the table as excel. This means I cannot use the export_csv example which is pure javascript.
I have no experience with JavaScript. All I want is to transfer a file from the directory where my main.py is to the client side.
The technique I have tried so far is to join a normal on_click callback to a button, export the information I need to 'output.xls', then change a parameter from a dummy glyph which in turn runs a Javascript code. I got the idea from Bokeh widgets call CustomJS and Python callback for single event? . Note I haven't set the alpha to 0, so that I can see if the circle is really growing upon clicking the download button.
At the bottom of my message you can find my code. You can see I have tried with both XMLHttpRequest and with Fetch directly. In the former case, nothing happens. In the latter case I obtain a file named "mydata.xlsx" as expected, however it contains only this raw text: <html><title>404: Not Found</title><body>404: Not Found</body></html>.
Code:
p = figure(title='mydata')
#download button
download_b = Button(label="Download", button_type="success")
download_b.on_click(download)
#dummy idea from https://stackoverflow.com/questions/44212250/bokeh-widgets-call-customjs-and-python-callback-for-single-event
dummy = p.circle([1], [1],name='dummy')
JScode_xhr = """
var filename = p.title.text;
filename = filename.concat('.xlsx');
alert(filename);
var xhr = new XMLHttpRequest();
xhr.open('GET', '/output.xlsx', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
alert('seems to work...');
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement("a");
link = document.createElement('a');
link.href = URL.createObjectURL(blob);
window.open(link.href, '_blank');
link.download = filename;
link.target = "_blank";
link.style.visibility = 'hidden';
link.dispatchEvent(new MouseEvent('click'));
URL.revokeObjectURL(url);
}
}
else {
alert('Ain't working!');
}
};
"""
JScode_fetch = """
var filename = p.title.text;
filename = filename.concat('.xlsx');
alert(filename);
fetch('/output.xlsx').then(response => response.blob())
.then(blob => {
alert(filename);
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement("a");
link = document.createElement('a')
link.href = URL.createObjectURL(blob);
window.open(link.href, '_blank');
link.download = filename
link.target = "_blank";
link.style.visibility = 'hidden';
link.dispatchEvent(new MouseEvent('click'))
URL.revokeObjectURL(url);
}
return response.text();
});
"""
dummy.glyph.js_on_change('size', CustomJS(args=dict(p=p),
code=JScode_fetch))
plot_tab = Panel(child=row(download_b,p),
title="Plot",
closable=True,
name=str(self.test))
def download():
writer = pd.ExcelWriter('output.xlsx')
data.to_excel(writer,'data')
infos.to_excel(writer,'info')
dummy = p.select(name='dummy')[0]
dummy.glyph.size = dummy.glyph.size +1
Trying out Eugene Pakhomov's answer, I found what was the issue.
The javascript code I named JScode_fetch is almost correct, however I get a 404 because it is not pointing correctly to the right path.
I made my application in the directory format: I changed my .py file to main.py, placed it into a folder called app, and changed this one line of code in JScode_fetch:
fetch('/app/static/output.xlsx', {cache: "no-store"}).then(response => response.blob())
[...]
You can see the problem was that it was trying to access localhost:5006/output.xlsx, instead of localhost:5006/app/output.xlsx. As it is in directory format, the right link is now localhost:5006/app/static/output.xlsx to count for the static directory.
I also changed a few lines in the download function:
def download():
dirpath = os.path.join(os.path.dirname(__file__),'static')
writer = pd.ExcelWriter(os.path.join(dirpath,'output.xlsx'))
writer = pd.ExcelWriter('output.xlsx')
data.to_excel(writer,'data')
infos.to_excel(writer,'info')
dummy = p.select(name='dummy')[0]
dummy.glyph.size = dummy.glyph.size +1
Now it is working flawlessly!
edit: I have added , {cache: "no-store"} within the fetch() function. Otherwise the browser thinks the file is the same if you have to download a different dataframe excel while using the same output.xlsx filename. More info here.
bokeh serve creates just a few predefined handlers to serve some static files and a WebSocket connection - by default, it doesn't have anything to serve files from the root of the project.
Instead of using the one-file format, you can try using the directory format, save your files to static directory and download them from /static/.
One downside of this approach is that you still have to write that convoluted code to just make your backend create the file before a user downloads it.
The best solution would be to go one step further and embed Bokeh Server as a library into your main application. Since you don't have any non-Bokeh code, the simplest way would be to go with Tornado (an example).
bokeh.server.server.Server accepts extra_patterns argument - you can add a handler there to dynamically create Excel files and serve them from, say, /data/. After all that, the only thing that you need in your front-end is a single link to the Excel file.

Generate office open XML excel file from javascript

Is there a way to generate an .xslx file from javascript and allow the user to download it by javascript? This page is geared towards being run offline in html 5 with no internet connectivity.
You could generate a data URI, and let the user save the link. However, IE8 has very limited support for data URIs. There is a 32 KB limit, and it's not allowed to be used with a href.
Also, you still need to find a actual XLSX JS library... But it is possible.
It has been done successfully by Ed Spencer. This project is using an EXT DataGrid as the source of the data, but I'm sure you could adapt it pretty easily.
**Yes You Can do it using javascript**
** call function expexcel('table_id','output_file_name');**
<script>
function expexcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
</script>
As Javascript has no file I/O, it's not going to be easy for your users to download. However, this kind of work is perfectly suited for a simple PHP script, which could generate your XSLX and save to your server dynamically.
You can generate any Office document with
OpenXML SDK for Javascript
http://openxmlsdkjs.codeplex.com/
As for allowing the user to save a file from JS I recommend FileSaver.js
https://github.com/eligrey/FileSaver.js/

Categories

Resources