AngularJS - show loading icon till csv file is downloaded - javascript

I have AngularJS application , and I send to download svc file on server like this :
public static void DownloadCSV(string csvFile, string fileName)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=" + fileName + ".csv;" +
"creation-date=" + DateTime.Now.ToString() + "; " +
"modification-date=" + DateTime.Now.ToString() + "; " +
"read-date=" + DateTime.Now.ToString());
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(csvFile);
HttpContext.Current.Response.End();
}
in client side I send to a webApi function called "exportToCsv" which use DownloadCSV function , in this way :
var p = document.createElement('a')
p.setAttribute('href', "myApp/exportToCsv" )
p.click();
My problem is that I want to present a loading icon to the user untill the file finish to download.
How can I do that?

Prepare an html with a loading icon(.gif probably) that is centered on screen, rest is shadowed maybe;
<div ng-show="loading" ng-include src="'loading.html'" ></div>
On JS side, before download start, set loading to true, when finished set it to false
$scope.loading = false; // when starts
$scope.loading = false; // when finished

Related

how to show an error when in appbrowser does not load error phonegap

i am developing an application and loading an hosted application using the inapp browser plugin cordova-plugin-inappbrowser
I have gotten most of the functionalities to work but i am unable to get the part of loading an error message when he url does not load, it dosent just work and shows me an error message of the url where i have hosted my application instead.
Which could be embarrassing.
please i need help on this
This is what am working with below thanks for ur potential responses
// my child browser code, the main source of my app content
function fire(){
var ref = cordova.InAppBrowser.open('http://####################', '_blank', 'location=no,zoom=no,hardwareback=yes,clearsessioncache=yes,clearcache=no');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', loadErrorCallBack);
ref.addEventListener('exit', inAppBrowserbClose);
}
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'");
}
}
Your code is generally fine, but you have no control over the title of the alert() function. You can use some other techniques to display the error message. For example, you can use a div:
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage = createMsg('Sorry we cannot open that page. Message from the server is: '
+ params.message);
inAppBrowserRef.executeScript({
code: scriptErrorMesssage
}, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function createMsg(msg) {
return 'var div = document.createElement("div");'
+ 'div.style.position = "absolute";'
+ 'div.style.top = "50%";'
+ 'div.style.left = "50%";'
+ 'div.style.width = "100px";'
+ 'div.style.height = "100px";'
+ 'div.style.color = "#f00";'
+ 'div.innerHTML = "' + msg + '";'
+ 'document.appendChild(div);'
}

get an image from local filesystem from javascript

I'm trying to get an image stored into a local filesystem. After that, I need to mount an html with this image from javascript.
So far, I'm getting the image with a servlet, and it's actually working as I can show the image in my JSP <img width="120" src="<%=IncVars.getParameter("ruta0")%>myImageServlet">
public class MyImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//get the file image
File image = IncFunctions.getLogoFile();
// Get content type
String contentType = getServletContext().getMimeType(image.getName());
// Init servlet response.
response.reset();
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
// Write image content to response.
Files.copy(image.toPath(), response.getOutputStream());
}
//...
}
I'm trying to do the same to mount the html from a js function, but I can't find the way to generate a html with this image in my js function:
function mountTicket(text, idControl, servletPath){
document.getElementById(idControl).innerHTML = parseTicket(texto, imagePath);
window.print();
}
function parseTicket(texto, servletPath){
var textHtml = "";
//Call the servlet
$.get(servletPath, function(data) {
textoHtml = "<img width='120' src=" + data + "/>";
textoHtml += "<br />";
});
//..
textoHtml += "<div";
if (estilo != ""){
textoHtml += " style=\"" + estilo + "\"";
}
textoHtml += ">" + contenido + "</div>";
return textoHtml;
}
The data var get from the servlet are bytes, and it seems the js doesn't know how to interpret it. I've also tried to pass the path of the image, let's say "C:\myDirectory\myImage.png", but as I expected, it couldn't find it and show it.
Any help would be appreciated. Thanks in advance.
The answer was easier than I thought. I don't need to call the servlet from my js code, I just need to add the image with the servlet path.
Something like this:
textoHtml = "<div><img src='" + servletPath + "'> </div>" ;
And the browser will show the image.
Hope it can help someone with similar "issues"

Real AJAX uploader - set file to upload manually

I used the Real Ajax Uploader (http://www.albanx.com/ajaxuploader) for uploading files from my js/jQuery based frontend to an ASP.net based server-side function - that works well by selecting files from the file-system as via the file dialog.
But now i need to find a way to set a file (i know the exact name and local path of the file) to upload automatically via a JS function instead of selecting it manually by clicking "select file" and selecting it from the file-dialog.
I think i have to manually create a file-object and push it into the files array (because of this description to get fiel infos : http://www.albanx.com/ajaxuploader/examples.php?e=6) but I can not manage setting a file and uploading it via my js function
Any help is highly appreciated
Thanks in advance
EDIT:
Thanks for responding Here is the code for taking a picture with the devices camera and pushing it into the files object of the uploader ...
that works so far, but i do not know how to update the fileuploader because it seems not to have a method to do this ...
so the file is in the file-list (file_list[0]) with all the parameters i think it dioes need, but it doesnt show up in the gui-file-list
regards Don
<code>
// photo functions
function getPhoto(){
navigator.camera.getPicture(onPhotoSuccess, onPhotoFail, {
quality: 50,
destinationType: Camera.DestinationType.NATIVE_URI
});
console.log("get photo ...");
}
function onPhotoSuccess(imageURI) {
console.log("photo taken ..." + imageURI);
$('#imgUploadArea').ajaxupload('clear');
var AU = $('#imgUploadArea').data('AU');
var file_list = AU.files; //get all the file objects
console.log("files: " + file_list.length);
// get the file object
window.resolveLocalFileSystemURL(imageURI, function(fileEntry) {
fileEntry.file(function(fileObj)
{
fileuploadShow("input.caseFormText.caseFormPhotoBtn");
// add the image
var capturedImg = new Object();
capturedImg.status = 0;
capturedImg.name = fileEntry.name;
capturedImg.path = fileEntry.fullPath;
capturedImg.size = fileObj.size;
capturedImg.filetype = "image.jpeg";
capturedImg.ext = "jpg";
capturedImg.AU = AU;
capturedImg.file = fileObj;
console.log("set image object to upload: " + capturedImg.path);
file_list.push(capturedImg);
console.log("files: " + file_list.length);
console.log("imgUpload ... imagedata path: " + file_list[0].path);
console.log("imgUpload ... imagedata name: " + file_list[0].name);
console.log("imgUpload ... imagedata status: " + file_list[0].status);
console.log("imgUpload ... imagedata size: " + file_list[0].size);
console.log("imgUpload ... imagedata filetype: " + file_list[0].filetype);
console.log("imgUpload ... imagedata ext: " + file_list[0].ext);
console.log("imgUpload ... imagedata file: " + JSON.stringify(file_list[0].file));
console.log("file added to filelist: " + file_list.length);
var files = $("#imgUploadArea").ajaxupload('getFiles');
console.log(JSON.stringify(files));
//$("#imgUploadArea").ajaxupload.('renderHtml');
//$("#imgUploadArea").ajaxupload('start');
});
});
}
function onPhotoFail(message) {
alert('Photo failed because: ' + message);
}
</code>
Don

Download file: ACCESS DENIED

I keep on having "ACCESS DENIED" after hitting my download button.
I already have full control on the specified folder.
I use this in jquery.
function DownloadFile(ProductNumber, File)
{
var windowSizeArray = ["width=400,height=400",
"width=500,height=600,scrollbars=yes"];
File = "C:/Documents and Settings/My PC/My Documents/" + File;
if (File != "")
{
var windowName = "popUp";
var windowSize = windowSizeArray[$(this).attr("rel")];
var exist = isExists(File);
if (exist)
{
window.open(File, windowName, windowSize);
}
else
{
ShowAlertMessage("The file for Product no. <a href='" + File + "' target='blank'>" + ProductNumber+ "</a> does not exist.");
}
}
else
{
ShowAlertMessage("No PDF file for Product no: " + ProductNumber+ ".");
}
}
You can't access local files like you do in your snippet.
You have to upload the file to the server and use PHP/another serverside language to do that. jQuery (or Javascript) only runs in the browser and does not have access to files outside it. Serverside web-languages only have access to files located on the server (or other servers using get_file_contents or cURL).
Your code looks like a C#/Java-source. They can access these local files.

Inherit just the javascript code from a master page

So I have a Javascript function on my master page. It works fine when I call it from pages that derive from this master page, however, on pages that don't, it obviously doesn't work. I am not able to put it in another .js file either because it uses some embedded c# code in it, so it has to be within a <script> tag.
This is the function:
function GridExport(viewUrl, fileName)
{
var actionUrl = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/ExportToExcel")%>";
var guid = GetGUIDValue();
window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName=" + fileName), null, null, null);
}
is there a way I can just include the Javascript definitions from my master page in another view without deriving from the master page?
You could create a UserControl containing this <script> or abstract out the actionUrl to a parameter of the GridExport function
function GridExport(viewUrl, fileName, actionUrl)
{
var guid = GetGUIDValue();
window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName=" + fileName), null, null, null);
}
Another handy way to avoid this path problem would be to have a global variable to define the root of the site:
var root = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/") %>";
then your function could always use this variable and append what it needs:
function GridExport(viewUrl, fileName)
{
var actionUrl = root + "mvc/Indications.cfc/ExportToExcel";
var guid = GetGUIDValue();
window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName=" + fileName), null, null, null);
}
Master pages can be embedded within each other. Why not just make a master page with only your javascript in it. Then make another master page that has the javascript master page as it's master. When creating new pages you can choose which one to use.
MasterPage1 -> Just javascript
MasterPage2 -> Contains your other stuff and has MasterPage1 as it's master
If you just want the javascript then user MasterPage1, for everything else user MasterPage2.

Categories

Resources