Change file name when using window.location to download - javascript

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"

Related

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 change filename when downloading file from server using javascript

I am downloading some images from facebook just for learning HTML and JS. But I don't want the filename to be some long string (contains some long string of numbers and chars ).
For eg I am using HTML5 download attribute
<a href="https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-xlt1/v/t1.0-9/12109181_503948273111743_2421725301227286538_n.jpg?oh=08c71f2236eaacc243ccd36475b4634e&oe=56BAA86C&__gda__=1459095933_f07fc4bb7bf54f48ac0b9286f8bc92c6"
download="imagename.jpg">
Download Image
</a>
Or this is JSFiddle of above code
When I click this link the file is download but with different name. My question is how do I change the filename something like images.jpg
Is it possible? If yes how should I go further.
The default filename is sent by the server through HTTP header:
Content-Disposition: attachment; filename='somefile'
Code that runs on the client has very limited control over files for security reasons. The only fix I can see is to have some server code which downloads the file from the other domain and then send it back with a new filename. So no, JS can't fix that for you.
I am relatively sure that the download attribute will only rename files that you are hosting, and not remote files.
You question is similar to this one:
Using download attribute with remote file
There is a workaround solution mentioned in that answer, but it's probably out of scope for just simple learning exercise.

downloaded data file from ajax

I am trying to initiate a file download through ajax. I can retrieve the data from the server, but cannot get the browser to open the data. I can't just point the browser's location.href at the endpoint url.
the resource I want to download is being exposed through an endpoint that requires custom http headers, and an authentication bearer token. I cannot change the backend api to allow cookies. Therefore, I cannot just open the url with window.open(url,'_blank')
I can make an ajax request to the endpoint, but I don't know how to download file after I get the response.
$.get( "restAPI/file.pdf", function( data ) {
var w = window.open(null,'_blank')
$(w.document.body).html(data);
});
Does not work either
I was hoping to do something similar to
var w = window.open(data,'_blank')
but that does not work either.
EDIT
The solution, thanks to joyBlanks
$http({method: 'GET',
responseType:'arraybuffer',
headers: {
Accept: 'application/octet-stream',
}, url:url }
).then(function(data) {
var blob = new Blob([data.data]);
if (window.navigator.msSaveBlob)
window.navigator.msSaveBlob(blob, filename);
else {
var link = document.createElement('a');
link.id = filename;
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}
});
Modern browsers support the download attribute for the <a> tag.
This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file. If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link (the user can change the name before actually saving the file of course). There are no restrictions on allowed values (though / and \ will be converted to underscores, preventing specific path hints), but you should consider that most file systems have limitations with regard to what punctuation is supported in file names, and browsers are likely to adjust file names accordingly.
Note:
Can be used with blob: URLs and data: URLs, to make it easy for users to download content that is generated programmatically using JavaScript (e.g. a picture created using an online drawing Web app).
If the HTTP header Content-Disposition: is present and gives a different filename than this attribute, the HTTP header has priority over this attribute.
If this attribute is present and Content-Disposition: is set to inline, Firefox gives priority to Content-Disposition, like for the filename case, while Chrome gives priority to the download attribute.
This attribute is only honored for links to resources with the same-origin.
<a download src="restAPI/file.pdf">Download File</a>
So when you click the a tag it will show a popup that will download the file. From the request I can see that the file is already available.
You can read about it more : https://developer.mozilla.org/en/docs/Web/HTML/Element/a
You won't be able to save the file from javascript. I would recommend you create an an API call that calls the restAPI and saves a temp file on your webserver. Then return the temp file name to the javascript and redirect to it. The browser should them prompt the user to open or save.
Here is another post that has more details on this approach:
Web Api won't download file using jQuery Ajax and Basic Auth

Need to download a file from webpage to local drive

I has a requirement like when user clicks on a download button instead of showing the content in browser, i want to save it to the localdisk(perticular location) of the user desktop. Is it possible to do??
If yes,Please help me with possibilities..
Thanks in advance
No a website can't decide where it can save something. Everything goes to download folder by default. You have to be using some sort of plugin with permissions or make like browser addon/extension.
If you want to prompt download then you could set send headers in php:
Content-Disposition: attachment; filename="fname.ext"
and
Content-Type: application/force-download
Or you could set attribute download to link in html
<a href="file.abc" download>Click Me</a>
Utility of HTTP header "Content-Type: application/force-download" for mobile?
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
http://www.php.net/manual/en/function.header.php
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes
You shall just point the file name like this to download.
But you cannot decide the path by your code.
Download the File
Note : Do not try this in jsfiddle or in codepen because they will rename the link with their custom so that the file will be displayed within their output. So, try it in your web server or in your localhost.

detecting Download file dialog?

is there any way i could detect opening of download file dialog box on web pages like hyperlink click event occurs and download file dialog box appears.... ??
and can i edit the filename in it ...... like attaching some website name along with filename .... so when the user download any file it automatically rename in to website-filename.pdf etc pro-grammatically
can we use input tag for it ?? or have to make customcontrols for it ??
thanks if any help provided
take care.
regards,
newbiefreak
You can just make a hyperlink with its href to a regular file, your browser will prompt to download it.
As for renaming the file, all you could do is create a special page which sends the file contents and correct headers, and specifying another name. You'll have to send the content-disposition header, as such:
Content-disposition: attachment; filename=yourfilename.extension
You can send a Content-disposition header to force a file downlaod box and specify a default filename.
http://support.microsoft.com/kb/260519
In regards to editing the filename:
HTML5 introduces a new attribute for a tags: download.
Using it forces browsers that support the attribute to prompt for a file download, rather than navigating to or attempting to open the linked file.
Also, whatever you value you assign to download will replace the file's actual name.
Source and demo: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

Categories