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.
Related
I am begginer in programming. I have made these stopwatch for speedsolves using HTML and JavaScript.
Is there any way of saving my average solve time using Javascript only?
For instance i have some variable with loop:
var time=0;
if (true){
time++;
}
and after I close the HTML site, close the browser and turn off the computer, after opening the site again I want to get var time=value before closing the site
I'm familiar with PHP and databases, but I dont really want to use it, since I have to start a server.
If you just want to save data for your program to read later, you can use localStorage or sessionStorage. That is, localStorage.setItem('name', 'value') and localStorage.getItem('name') to read it. (They're the same, except sessionStorage gets cleared once the browser is closed, while localStorage doesn't.)
To actually save a file, you can do that only by triggering it to be downloaded. First you create a Blob with the content you want for the file, then you get an object URL for that Blob. Assign the URL to the href of a link with a "download" attribute and click it.
function saveFile(contents, name) {
const blob = new Blob([contents], {type: 'text/plain'});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = name;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Little more information will help, but, as you are talking of storage, you can use localstorage or sessionstorage within javascript to store the values.
For saving files on the local device, you can use FileSaver. But in your situation, an easier solution would be to take advantage of localstorage.
Note: From what I've found, LocalStorage won't work without a server. So if you want to store data and aren't using a server, FileSaver may work better. Then again, I don't know if it's possible to load the data in a file saved in FileSaver into javascript in a browser, especially if you don't have a server
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)
}
I'm using window.location to download my image. It isn't in HTML because I generate the image on the server and then send it back down so it looks like :
window.location = data.url;
I've seen a few other questions but they suggest the download attr which I don't have because there's no HTML.
Is there a way I can change the file name?
Front-end solution
The only thing you can do on the front-end side is to change your code to HTML <a> element with download attribute:
Download
When user clicks this link, the browser forces download and saves the file with given filename. You can read more about it in this post. It's quite a new feature so check the browser support.
Back-end solution
If you can modify the server-side code then you should use content-disposition header as defined in RFC 2183.
content-disposition: attachment; filename=very_important_report.pdf
I've been wondering about it as well and saw this post but I was also using vuejs for the project and want the export to be continues even when switching from one page to another so I tried something and it did work here is another solution:
var link = document.createElement('a');
link.setAttribute('href', '<yourlink_or_data>');
link.setAttribute('download', 'filename.ext');
link.click();
You can't change the filename on the client side. You would have to do that on the server.
You could set the content-disposition header (on the server side) like this:
Content-Disposition: attachment; filename="yourname.gif"
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
For one of our customer, we are required to use HTML File Input control, to upload the file to another server using REST Web Services. I was able to achieve this using HTML FileReader.readAsArrayBuffer Method. But since users are using IE8 and IE9, HTML5 APIs are not supported. I tried using below code, but this reads only TXT file not other file types like DOCX or PNG
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
I use file inputs in a weird working way in IE8, maybe it can help you:
var form = document.createElement("form");
form.method = 'POST';
form.action = url;
form.target = '_blank';
form.encoding = form.enctype = "multipart/form-data";
form.appendChild(fileInput);
document.body.appendChild(form);
form.submit();
It sends the file chosen via fileInput as a POST request to the server, without reading its binary content. Do you absolutely need to read the file client-side ?
If you need cross-site upload, I think there are some iframe hacks for IE working.
Thank You for your quick response. The Web service which I am using is RESTfull service and accept the file as Base64string. So I need to read the file content at client side itself, convert it as Base64 String and pass it to the WebService. So I cannot use Post in there.
This is fully-being a client-side dependent script and at same time there is no handle at server side component I tried options of using ActiveX, but due to some security reason, we cannot proceed with that. I also tried ADO.Stream but even that uses ActiveX.
Thanks,
Aravind