JavaScript to .csv download fails: "Failed. No File" - javascript

Right now I'm just trying to get anything to work. My browser is Chrome 40.022. When I click my download link, it initiates downloading but then fails with the error Failed. No file. What am I doing wrong? Is this a browser thing?
Javascript:
var fileName = "data.csv";
var csv = "abc, def, hij";
//I'm partially using angular in this page...
$scope.link3 = 'data:text/csv;base64,' + btoa( csv ); //forgive the variable name
HTML:
<a ng-href="aap.link3" download="data.csv">Hello</a>

I created a jsfiddle for your problem. There are 2 issues with your code:
In your case, ng-href data need to be interpolated
You must add data into whitelist for Href attrtibute, else it will
be transformed into 'unsafe'.
https://jsfiddle.net/8o1v1uym/

Related

Window.location file download

I am trying to download a file to client side using following javascript code:
window.location = InsightRoute + "GetOrderXML?orderNumber=" + txtOrderNoVal
If the file is available then it will get downloaded to the client machine. But the issues is if no file is available for downloading, it
will simply gets redirect to a blank page
http://mysite/GetOrderXML?orderNumber=1
You should check whether the file is available for downloading before redirecting, for example like this:
if (sdpInsightRoute && txtOrderNoVal)
window.location = sdpInsightRoute + "GetOrderXML?orderNumber=" + txtOrderNoVal
This way, if the variable txtOrderNoVal is undefined, the redirection wouldn't take place.
If file is not available then use following code inside controller, so that the alert will pop up:
Response.Write("<script>alert('Item does not exist on this environment.');window.history.go(-1);</script>");
return null;
Use of: window.history.go(-1); If there is no file and since it is getting redirected to a new page: http://mysite/Insight/GetOrderXML?orderNumber=1, which can be avoided.

set file attribute filesystemobject javascript

I have created a file as part of a script on a network drive and i am trying to make it hidden so that if the script is run again it should be able to see the file and act on the information contained within it but i am having trouble doing this. what i have so far is:
function doesRegisterExist(oFs, Date, newFolder) {
dbEcho("doesRegisterExist() triggered");
sExpectedRegisterFile = newFolder+"\\Register.txt"
if(oFs.FileExists(sExpectedRegisterFile)==false){
newFile = oFs.OpenTextFile(sExpectedRegisterFile,8,true)
newFile.close()
newReg = oFs.GetFile(sExpectedRegisterFile)
dbEcho(newReg.Attributes)
newReg.Attributes = newReg.Attributes+2
}
}
Windows Script Host does not actually produce an error here and the script runs throgh to competion. the only guides i have found online i have been attempting to translate from VBscript with limited success.
variables passed to this function are roughly declared as such
var oFs = new ActiveXObject("Scripting.FileSystemObject")
var Date = "29-12-2017"
var newFolder = "\\\\File-Server\\path\\to\\folder"
I know ActiveX is a dirty word to a lot of people and i should be shot for even thinking about using it but it really is a perfect fit for what i am trying to do.
Please help.
sExpectedRegisterFolder resolves to \\\\File-Server\\path\\to\\folder\\Register which is a folder and not a file.
I get an Error: file not found when I wrap the code into a try/catch block.
I tested the code on a text file as well, and there it works.
So you're either using the wrong method if you want to set the folder to hidden.
Or you forgot to include the path to the text if you want to change a file to hidden.
( Edit: Or if Register is the name of the file, add the filetype .txt ? )
If you change GetFile to GetFolder as described in https://msdn.microsoft.com/en-us/library/6tkce7xa(v=vs.84).aspx
the folder will get hidden correctly.

How to start browser file download from javascript, only if a web service returned correct content

I need to build javascript that triggers on a click to <a> element and invokes a GET call to a web service (I am coding the service also).
The service should return a file and only if no error occurred offer it for user to download from browser, otherwise leave him on the page where some other component will render the error.
The way I know to do it is to set "href" attribute of the <a> element to the URL of the service.
Due to the specifics of the app I am building this for, I am not returning an error but html with "errorOccurred" content (it might be file with the same content too).
So, my question is: how to start file download from a javascript method (I am using jQuery.ajax) I have attached to onclick attribute of <a> element only if the retrieved file content is ok?
A solution found here
I am copy pasting the code given there:
var textToSave = 'this is a test';
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.txt';
hiddenElement.click();
Ok. You have control over the service so instead of returning html with a textual error message when the service fails, return a 400 type error.
Then in your jQuery.ajax do something like this:
jQuery.ajax {
dataType:....
url:...
data:...
success:...
error: function(){
alert('Your error message');
}
}
If you are using PHP on the server side, you can use the following to generate a 400 type error:
header('HTTP/1.1 404');
Try searching for "errorOccurred" text in the HTML document.
Use the "indexOf" method to see if the string exists in the returned HTML.
if(returnedText.indexOf('errorOccurred') > -1) {...code to download file}

Create file to download js

I'm receiving a JSON output from an API, and i want to use it with JS and also save that output to file. Is there any way to trigger the browser download machanism using JS with thet output?
Maybe now some browsers support the attribute download but you don't trigger the browser to automatically download the file.
the only way i know is #BAS's solution but without a filename.
tested in chrome ..
array=[{a:'1',b:'2'},{x:'3',y:'4'}];
function dl(array,filename){
var b=document.createElement('a');
b.download=filename;
b.textContent=filename;
b.href='data:application/json;base64,'+
window.btoa(unescape(encodeURIComponent(JSON.stringify(array))))
// or
// b.href='data:application/javascript;charset=utf-8,'+JSON.stringify(json);
return b
}
document.body.appendChild(dl(array,'my.json'));
example
http://jsfiddle.net/8yQcW/
UPDATE direct download works ... on chrome i tested.
on append simulate click
var e=document.createEvent('Events');
e.initEvent('click',true,false);
document.getElementById('dl').dispatchEvent(e);
http://jsfiddle.net/8yQcW/1/
You could try it with a data URI:
function triggerDownload(json) {
var dataUri = 'data:text;charset=utf-8,' + json;
window.open(dataUri);
}
Try entering data:text;charset=utf-8,{"Key":"Value"} into your browsers address bar. It should show you the save dialog.
See here for more information and browser support.

Fake file upload in Chrome not showing file name

I'm trying to use the solution over at quirksmode.org to sort the file upload input inconsistency problem, using the following javascript:
$('.sidebar-uploadcv input[type=file]').attr('onchange','javascript:document.getElementById("fakeupload").value = this.value').addClass('file_input_hidden');
The trouble is, this doesn't work properly in Chrome. It renders and the user can click to choose a file, but the filename isn't then displayed in the #fakeupload input.
Can anyone help?
Found the solution by invoking .change() instead of .attr('onchange',...). This method works cross-browser.
To get rid of the fakepath string in Webkit et al I've also added the var filename... line to strip out that part of the file name.
$('.input[type=file]').change( function() {
var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
$('#fakeupload').val( filename );
});

Categories

Resources