Javascript Exporting data to a CSV file - javascript

I've found some code in here on how to export data from an array to a CSV file. I just have a few problems that needs to be address since I'm not very familiar with the code that I got.
listofconstraints.forEach(function(infoArray, index){
dataString = infoArray.join(",");
csvContent += dataString + "\n";
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "listofconstraints.csv");
link.click();
It works properly but it lacks some of the features that I need including, checking if the file already exists, setting the path of the file, and if it does exists, overwriting it.

JavaScript cannot exert any control over the visitor's local filesystem. Visitor remains in complete control of where downloaded files go, what they are named, and indeed whether he even wants to download them in the first place.
When you download a file from any web site, the browser asks you where you want to store the file, and if in that location there is another file named like it already then it will rename your file like file (0).csv

Related

How can I download text from an HTML text area as a .txt file using JS?

I'm working on a project that randomly generates a set of characters intended to be used for a password and want the user to be able to download the results as a text file. I've read some things on BLOBs and a few other methods that haven't worked. It'd be a big help if someone could offer a method that works.
TL;DR: Need a way to download text from an HTML textarea as a .txt file using JS
You should be able to programmatically create a link that uses a data url with your text, add a download attribute so the browser downloads instead of navigating (and to specify a filename), and click it.
This doesn't run as a SO snippet, presumably for security reasons, but it should work out in the world (and you can copy/paste this in your dev tools console to test it):
const generatedText = 'some generated blob of text';
// create an anchor element that we can programmatically click
const a = document.createElement('a');
// set up a data uri with the text
a.href = `data:text/plain,${generatedText}`;
// set the download attribute so it downloads and uses this as a filename
a.download = 'the-name-of-the-file.txt';
// stick it in the document
document.body.appendChild(a);
// click it
a.click();

Creating a temporary file and opening it in a different app on the user's computer

I'm coding an internal corporate website that, among other things, produces and renders XML files. These files generally aren't meant to be saved directly, and the user should rarely need to view them raw in the first place. However, the site can download and open a file in an XML processor installed on the user's computer.
The website was originally written for Internet Explorer 6, and I'm trying to upgrade it to be compatible with modern browsers. The code it initially used, compatible with IE6, was this:
function XmlOpen(path) { // path = "C:/Program Files/path/to/executable.exe", hardcoded
// xmlOutput is a global variable containing the raw XML to be saved
if (xmlOutput) {
// global variable to cache most recently downloaded file. If the XML is regenerated
// this will be reset
if (!xmlTempPath) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var tempfolder = 2;
var tfolder = fso.GetSpecialFolder(tempfolder);
var tname = fso.GetTempName();
var tempfile = tfolder.CreateTextFile(tname);
tempfile.writeline(xmlOutput);
tempfile.close();
xmlTempPath = tfolder.Path + '\\' + tname;
}
var shell = new ActiveXObject("WScript.Shell");
var cmd = '"' + path + '" "' + xmlTempPath + '"';
shell.Run(cmd);
}
return false;
}
Ideally, my requirements for the rewrite are that it require as little user interaction as possible beyond the initial click.
My basic approach is to, instead of using ActiveXObjects, use registry keys to tag the appropriate XML programs. These can be installed during onboarding, when also installing all our other internal tools, so I figure I should just be able to open a url as xmlprogram://filename and have it work, as long as I have a file to go with it.
I can also easily download a file, by just writing the XML into a blob, generating a random filename, and having a download prompt appear. But then I don't know the folder and actual name with which the file was downloaded, so I can't automatically have it open with the xmlprogram:// url. Thus, I need to somehow save the file temporarily somewhere my javascript knows the full path to, and invoke the user's program on it using the link. But from what I've been able to find, it's presently impossible to write an actual temporary file on the user's computer, and you can't make localstorage be treated as a file.
tl;dr How do I save a temporary file to the user's computer such that I know the location to which it was saved and can have them open it in a different program automatically?
According to your question, as far as I know it is impossible. Pure browser-JavaScript is not be able to get information about the user's filesystem. The default download path might also contain risk information.
And the file download location depends on the settings in the browser, you can't bypass this setting, otherwise it will violate the user's security.

Save/log HTML-Object into the file

Would it be possible to implement google-analystics like feature, which on page load would append the existing file located on the server with the current href? Is this achievable with js?
It is achievable with JS. but if you're thinking of doing it only with client side JS (presumption), that won't work, you need to have a server.
Only server side code would have the right access to add contents to a file on server.
It depends on what you need to obtain.
If you just want the user to save some data available on the shown page you can obtain a similar risult with a trick without server side code.
Here's a small example using jQuery:
var fileContent = "test";
var encodedUri = encodeURI(fileContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
If, on the other hand, what you need is specifically file manipulation on the server then my suggestion is to use node.js or any other server technology to achieve such a result.

How to Download multiple files from javascript

I am trying to use window.location.href in a loop to download multiple files
I have a table in which i can select file's, then i run a loop of selected and
try navigate to the file path to download the files.
I keep only getting the last file to download.
I think it's due to the location herf only taking action after my javascript finishes and not as the code runs.
When i have a break point on the window.location.herf it still only downloads the last file and only when i let the code run through.
Is there a better way to initiate multiple downloads from a javascript loop.
$("#btnDownload").click(function () {
var table = $('#DocuTable').DataTable();
var rows_selected = table.rows('.selected').data();
$.each(rows_selected, function (i, v) {
window.location.href = v.FilePath;
});
});
In some browsers (at least Google Chrome) support the follow:
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
JSFiddle: https://jsfiddle.net/padk08zc/
I would make use of iframes and a script to force the download of the files as Joe Enos and cmizzi have suggested.
The answer here will help with JavaScript for opening multiple iframes for each file:
Download multiple files with a single action
The answers for popular languages will help with forcing downloads if the URL is actually something that can be served correctly over the web:
PHP: How to force file download with PHP
.Net: Force download of a file on web server - ASP .NET C#
NodeJS: Download a file from NodeJS Server using Express
Ruby: Force browser to download file instead of opening it
Ensure you change the links to point to your download script and also make sure you add the appropriate security checks. You wouldn't want to allow anyone to abuse your script.
Though this looks like an old post and I stumbled on this while trying to solve a similar issue. So, just giving a solution which might help. I was able to download the files but not in the same tab. You can just replace the event handler with download which is provided below. The urls is an array of presigned S3 URLs.
The entire code looks like below:
download(urls: any) {
var self = this;
var url = urls.pop();
setTimeout(function(){
var a = document.createElement('a');
a.setAttribute('href', url);
document.body.appendChild(a);
a.setAttribute('download', '');
a.setAttribute('target', '_blank');
a.click();
// a.remove();
}, 1000)
}

when i downloading a zip file Every time name is changing i write the following code for download the zip file

When I downloading a zip file Every time name is changing
I write the following code for download the zip file.
var url = Mypath1 + "DownloadFiles/DeliveryOrders.zip";
window.open(url, '_self', 'Download', false);
It's because windows don't overwrite your files and appends (##) to the end of your file names.
When your browser is determining what file name to use to save the HTTP resource to:
it is looking at the URL
using that to select its first choice
looking in your downloads folder and seeing that a file of that name already exists
adding a number so that it doesn't overwrite the file
This is normal behaviour.
You can't change that browser behaviour.

Categories