Open Save As Dialog box using jQuery/Javascript after csv file download - javascript

I'm trying to open save as dialog after user click a button but it takes to file to downloads folder. I want to prompt the user where to save the file.
Here is my Javascript function I have so far:
function exportOBCSerialsToCSV(e) {
var dataSource = $("#vehicleGrid").data("kendoGrid").dataSource;
var filteredDataSource = new kendo.data.DataSource({
data: dataSource.data(),
filter: dataSource.filter()
});
filteredDataSource.read();
var data = filteredDataSource.view();
var result = '';
for (var dataRow = 0; dataRow < data.length; dataRow++) {
result += data[dataRow].OBCSerial + ',';
if (dataRow == data.length - 1) {
result += data[dataRow].OBCSerial;
}
}
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(new Blob([result]), 'OBC Serials.csv');
}
else if (window.URL != null) {
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'OBC Serials.csv';
a.click();
}
else {
window.open(result);
}
e.preventDefault();
}

Below possibilities :
Set the header of the file on the server, like so:
Below possibilities :
1. Set the header of the file on the server, like so:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
The download attribute does not allow you to change the filename or filetype any more as it is an obvious security risk.
What you are trying to do it replicate the right-click - save-as dialogue but I'm afraid that is not possible at this time.
2. When user's browser is set to automatically download all files in default location which is why not only this file but all other files from user's browser were downloaded directly without the save prompt dialogue. Changing the settings in browser to 'always ask the download location' can work.
The download attribute does not allow you to change the filename or filetype any more as it is an obvious security risk.
What you are trying to do it replicate the right-click - save-as dialogue but I'm afraid that is not possible at this time.
When user's browser is set to automatically download all files in default location which is why not only this file but all other files from user's browser were downloaded directly without the save prompt dialogue. Changing the settings in browser to 'always ask the download location' can work.

Related

Download File to Specific Directory JS

I'm taking inputs from an HTML form and putting them into a file. I've currently got it so it automatically downloads the file to the downloads folder but I want it to download to a specific directory:
%AppData%/Code/User/snippets/
Here is the code I've got at the moment:
function createSnippet() {
var snipName = document.getElementById('snipName').value;
var snipScope = document.getElementById('snipScope').value;
var snipPrefix = document.getElementById('snipPrefix').value;
var snipBody = document.getElementById('snipBody').value;
var snipDesc = document.getElementById('snipDesc').value;
// Final
let CONTENT = (`
{
"${snipName}": {
"scope": "${snipScope}",
"prefix": "${snipPrefix}",
"body": [
"${snipBody}"
],
"description": "${snipDesc}"
}
}
`);
var a = document.createElement("a");
a.href = window.URL.createObjectURL(new Blob([CONTENT], {type: "text/plain"}));
a.download = `${snipName}.code-snippets`; // I want this to download to the directory shown above
a.click();
}
Using JS, this cannot be done. If your trying to download a file to specific destination in the drive it is not possible. This possess a huge security risk if browsers allow it.
When a user is viewing a website, they are using a browser to access the webpage and browser decides what all permissions a website can have and what limitations it should put.
The only way that you download a file in specific folder is,the user doing to himself. Otherwise downloads made by browser will be stored at some default destination like /user/Downloads or user chosen path /user/Downloads/Chrome_Downloads.

New window and incorrect filename when saving data as CSV file

I am getting some CSV data from an Ajax request. I am trying to use FileSaver.js (https://github.com/eligrey/FileSaver.js/) to enable the end-user directly download this data as a CSV file.
This is the code used in my Ajax request handler.
jQuery.post(urlPrefix + "/api/ReportData",
dataToPost,
function (data, status) {
var blob = new Blob([data], { type: "text/csv" });
var fileName = "";
fileName += "Data-Export";
fileName += ".csv";
saveAs(blob, fileName);
});
This code is called from a button click event. Whenever the code executes, a new tab is opened, and the file is saved without a csv extension. In fact, the downloaded file has no extension at all. See the attached screenshot for details. The (7) is due to this being my seventh download.
The actual file that is saved is a valid file. If I manually set its extension to csv, I can use it properly. But I want to know how to use FileSaver to generate appropriate extension, and also download the file without opening a new tab.
What I have already tried
Export to CSV using jQuery and html
I found out this link https://code-maven.com/create-and-download-csv-with-javascript where it is possible to create a hidden anchor tag and download the file.
My new code is below
jQuery.post(urlPrefix + "/api/ReportData",
dataToPost,
function (data, status) {
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(data);
hiddenElement.target = '_blank';
hiddenElement.download = 'Exported-Data.csv';
hiddenElement.id = "customTemporaryAnchor";
hiddenElement.click();
jQuery("#customTemporaryAnchor").remove();
});
When this code is executed, the file downloads with proper extension, and without any popup or new tab.

Open file from Firebase Storage in new table and not download

I have various buckets in Firebase Storage that all contain an html file. What I want to do is through Javascript, get the URL of a particular HTML file in a bucket, and then open it in a new tab. When I use the 'getDownloadURL' method, and pass the url to window.open what I'm finding is that a new tab opens temporarily, the file gets downloaded, and then the tab closes. Ideally, I would like to completely avoid downloading the file, and just view it. I believe this is happening because of the format of the URL itself:
https://firebasestorage.googleapis.com/v0/b/[project].appspot.com/o/[bucket]%2Fcreate.html?alt=media&token=[token]
Can anybody please help me use window.load to only open the html file in a new tab? I would prefer to not download the file at all, and I need the tab to remain open. Thanks in advance for any help!
var storage = firebase.storage();
var storageRef = storage.ref();
var reportFileRef = storageRef.child(currentUid + '/create.html');
reportFileRef.getDownloadURL().then(function(url) {
window.open(url, '_blank')
});
Setting the metadata correctly solved the Content-Disposition issue. Here is the function I've defined, where contenttype is either "text/html" or "image/png"
def uploadToFirebaseStorage(filename, filepath, user, report, contenttype):
my_file = open(os.path.join(filepath, filename), "rb")
my_bytes = my_file.read()
my_url = "https://firebasestorage.googleapis.com/v0/b/[project].appspot.com/o/" + filename
my_headers = { "Content-Type": contenttype }
my_request = urllib.request.Request(my_url, data=my_bytes, headers=my_headers)
try:
loader = urllib.request.urlopen(my_request)
except urllib.error.URLError as e:
message = json.loads(e.read())
return message["error"]["message"]
else:
return loader.read()

How do I force download with html/javascript in a jsp from IE 9 and above?

I have a link to an img
Save
and i need that this link make direct download of this file.
On Chrome and Firefox works fine with the attribute 'download'
<a href="relative_Path_of_IMG" download>Save</a>
but on ie this doesnt works fine.
I have found on internet the JS comand window.document.execCommand and i try to use on this way
window.document.execCommand('SaveAs', true, fileName || fileURL)
but this way open a window to the user chose a folder to save, and i need that the download execute automaticaly on the default folder of downloads of the user, like attribute download works on Chrome and Firefox.
Thanks
Paulo Filipe
You can create a JSP and use it as a servlet. It'll recieve a link by parameter with the url of image that you want download.
This servlet will open a stream to read the file and other stream to write the output on your browser. With this your browser will be responsable to handling your file.
Follow a example of this JSP.
<%# page language="java" contentType="image/jpeg; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String urlPrefix = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
String fileUrl = request.getParameter("fileUrl");
if (fileUrl == null || "".equals(fileUrl.trim())) {
throw new Exception("No image Found.");
}
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8"));
String fullEncodedUrl = urlPrefix + URIUtil.encodePath(fileUrl);
URL url = new URL(fullEncodedUrl);
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ((len = stream.read(buf)) > 0) {
outs.write(buf, 0, len);
}
outs.close();
%>
The user should get a choice of where to save files. Its only fair, since the download is going onto their machine.
In Chrome and Firefox there is a choice in settings that (in Firefox) defaults to always saving the files to the Downloads folder. The user chose to always save to the same folder by not changing that setting. They could just as easily change to the next setting saying "Always ask me where to save files." But THEY choose, not the website. If Microsoft had a similar option the user could choose it, but you (i.e. any server-side code) cannot.

Start downloading file using JQuery

I want to start file downloading when I clicked the button.
I just have the path of the file.
How can I start downloading?
This is what I tried so far:
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
var do = 'file';
$(body).append(do);
});
What I am doing wrong.
I never want to redirect the page.
Is downloading start in browser or in software for downloading files if installed on client machine
Alternatively you can also set the top.location
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
top.location.href = filepath;
});
You cannot force a file to be downloaded in JavaScript.
What you can do is location.href = "somefile.ext";, however it will only be downloaded if the server includes Content-Disposition: attachment as one of its response headers to that file request.
If you want to download a file to the client, then do this:
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
location.href = filepath;
});
location.href will look for a page, but it will not find anything, so it will download the file instead.
You can create a form using jQuery and use the submit function. This will not change the URL in the address bar.
$('#download_button').click(function(){
var filepath = $(this).attr('data-filepath');
var form = $('<form>').attr('action', filepath);
form.submit();
});

Categories

Resources