Call to API REST and download the zip file to the computer - javascript

I have the following piece of code:
jQuery.ajax({
type: "GET",
url: "http://localhost:8081/myservicethatcontainsazipfile",
contentType:'application/zip',
success: function (response) {
console.log("Successful");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error.");
}
});
According to AJAX specifications, you can't download a file directly to the computer (security reasons), so I would like to know how can I download this file directly from the client without having to create and click an html element and similar options?

You cannot do it with AJAX. But, you can redirect / open a new window that takes the user to the file page, which will automatically start the download.
If you want no button you can use one of these lines of JavaScript.
window.open(download_url, '_blank')
window.location = 'download_url'
Take in mind that for security reasons you will need to wait for at least 3-5 seconds before starting the download.
setTimeout(() => window.location = 'download_url', 5000);
You should also have a look at How to start automatic download of a file in Internet Explorer?

You can also look at filesaver.js
https://github.com/eligrey/FileSaver.js/

Related

Urls that don't finish with / won't load properly other embebed pages

Has anyone encountered this problem?
I have been working with c# MVC in Visual Studio and when we publish our pages if the user tries to access the page and doesn't end the URL with / some pages won't load properly.
We use a lot that we have a main page and then somewhere in the middle is a div that is updated through javascript (I know that's what the render from mvc does when using the layout, but our boss doesn't like it that way and also it tends to interfere with her multiple layers of javascript)
It is these div parts that are loaded this way that won't load when the main page doesn't have a / at the end.
we have tried using #url.action and also hard typing the URL of the second page in the javascript and both yield the same result.
Is there a way to configure the project so that it doesn't matter whether the url that was typed in the browser has the / at the end?
EDIT: Added javascript function
function refreshdiv(divid, url) {
var seconds = 15;
$.ajax({
type: 'POST',
url: url,
context: document.body,
async: true,
timeout: 15000,
success: function (data) {
$("#" + divid).html(data);
$("#" + divid).find("script").each(function (i) {
eval($(this).text());
});
}
});
Thanks in Advance for any help

IE is not refresh after call the download function

In the jsp, I use javascript, jquery and json to call a function for download, once the the download is finished, it will return the the current page.
However the problem is although the download is complete, I can able to download and view the file. In the screen, it still show the message indicate it is downloading.
I read this post, the accepted solution mentioned to disable the cache with ajaxSetup. I read my code, I have already include it in the code, however the Internet Explorer still not return to proper page when the download finished. Is there any method I can use to solve the problem. Thank you.
function startDownload() {
$.blockUI({ message: '<h1>Downloading, please wait...</h1>' });
var i = setInterval(function() {
$.ajaxSetup({ cache: false });
$.getJSON("ThePage/downloadProgress?jsoncallback=?",function(download_token) {
if (download_token.fileDownloadToken == "finished" ) {
$.unblockUI();
clearInterval(i);
}
});
}, 1000);
}
Update
I mentioned it occurs on IE because our company is mainly using IE for the web browser. So I intend to make to code works on the IE first. Sorry for the inconvenience that I have made.

I'm using (unlink($_GET['videofile'])) and it works fine on dev server but in prod won't work

Hi I'm loading a table with files on a server folder, each row has a "Delete" link that when clicked, it should unlink/remove the file from the server. The code works perfectly fine on my dev server, however, when in prod it doesn't work. I have checked all the code and there doesn't seem to be any difference on the code. I'm not sure if I'm missing some permission related thing on my prod server, but when I click on "delete" the files are not deleted at all. It runs the function below as if it is doing it but the file is still there.
The addfile.php contains:
if (unlink($_GET['videofile'])) {};
The javascript function
function deleteVideo(file_path)
{
var r = confirm("Are you sure you want to delete this Video?");
var j = document.getElementById('vid').value;
if(r == true)
{
$.ajax({
url: 'addfile.php',
data: {'videofile' : file_path },
success: function (response) {
alert('Your file has been removed');
showVideos(j);
},
error: function () {
alert('There was an error removing the file, please try again');
}
});
}
}
The "delete" link looks like:
deleteVideo("videopath")
In your production server, check if your httpd server has permissions to write in video folder.
Take care of allowing unlink a file thought its path, it may be very dangerous. Instead, register your video path on a database, and then passes to function only the ID of video. Also, make sure your user is deleting only the videos he can delete, according to your business rules.

jQuery check if a file exist locally

I am developing a local site for a company (only local internal use, offline and without server). I have a main page that has a main div, that contain 3 different div. Each div is linked to a page and the "onclick" event of each div will load the page linked into the main div. So i have to check, with the document ready function, if each page exists and, if not, I want to delete the div linked to that page. How can I check if a page exist locally? I've found many answere that check with status of connection if a page exists, but my html will only work offline and locally, so I can't use that method.
EDIT - SOLVED
I've solved this using the script of #che-azeh:
function checkIfFileLoaded(fileName) {
$.get(fileName, function(data, textStatus) {
if (textStatus == "success") {
// execute a success code
console.log("file loaded!");
}
});
}
If the file was successfully load, i'd change the content of a new hidden div that will tell to another script if it have to remove or not each of the three div.
This function checks if a file can load successfully. You can use it to try loading your local files:
function checkIfFileLoaded(fileName) {
$.get(fileName, function(data, textStatus) {
if (textStatus == "success") {
// execute a success code
console.log("file loaded!");
}
});
}
checkIfFileLoaded("test.html");
I suggest you run a local web server on the client's computer. (See also edit below on local XHR access).
With a local web server they can start it up as if it was an application. You could for example use node's http-server. You could even install it as an node/npm package, which makes deployment also easier.
By using a proper http server (locally in your case) you can use xhr requests:
$(function(){
$.ajax({
type: "HEAD",
async: true,
url: "http://localhost:7171/myapp/somefile.html"
}).done(function(){
console.log("found");
}).fail(function () {
console.log("not found");
})
})
EDIT:
Firefox
Another post has (#che-azeh) has brought to my attention that firefox does allow XHR on the file "protocol". At the time of this writing the above works in firefox using a url of just somefile.html and using the file scheme.
Chrome
Chrome has an option allow-file-access-from-files (http://www.chrome-allow-file-access-from-file.com/). This also allows local XHR request
This flag is intended for testing purposes:
you should be able to run your tests in Google Chrome with no hassles
I would still suggest the local web server as this make you independent of these browser flags plus protect you from regression once firefox/chrome decide to disable support for this.
You can attempt to load the page within a try-catch construct. If the page exists, it will be loaded though. If it doesn't, you can (within the catch) set the related div as hidden.
Try to access the page using $.ajax. Use the error: option to run a callback function that removes the DIV linked to the page.
$.ajax({
url: "page1.html",
error: function() {
$("#page1_div").remove();
});
You can loop this code over all the DIVs.
You can use jquery load function
$("div").load("/test.html", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$(this).html(msg + xhr.status + " " + xhr.statusText);
}
});

how to load google client.js dynamically

this is my first time to post here on stackoverflow.
My problem is simple (I think). I am tasked to allow users to sign up using either Facebook, Google Plus, LinkedIn and Twitter. Now, what I want to do is when the user clicks the Social Network button, it will redirect them to the registration page with a flag that determines which social network they want to use. No problem here.
I want to load each API dynamically depending on which social network they choose.
I have a problem when loading the Google JS API, dynamically. The sample found in here loads client.js in a straightforward manner. I have no problems if I follow the sample code. But I want to load it dynamically.
I tried using $.ajax, $.getScript and even tried adding the script to the page just like how you call Google Analytics asynchronously. None of the above worked. My call back function is NOT called all the time. Also, if i call the setApiKey from the call back function of $.ajax and $.getScript, the gapi.client is NULL. I don't know what to do next.
Codes that did not work:
(function () {
var gpjs = document.createElement('script'); gpjs.type = 'text/javascript'; gpjs.async = false;
gpjs.src = 'https://apis.google.com/js/client.js?onload=onClientLoadHandler';
var sgp = document.getElementsByTagName('script')[0]; sgp.parentNode.insertBefore(gpjs, sgp);})();
Using $.getScript
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
Using $.ajax
$(document).ready(function () {
$.ajax({
url: "https://apis.google.com/js/client.js?onload=onClientLoad",
dataType: "script",
success: function () {
console.log("GP load successful");
SetKeyCheckAuthority();
},
error: function () { console.log("GP load failed"); },
complete: function () { console.log("GP load complete"); }
});});
May I know what is the proper way of calling this js file dynamically? Any help would be appreciated. Thank you.
Ok, I just thought of a solution but i think it's a bad one. Please let me know what you think of it.
i used $.getScript to load the js file
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
and then on my SetKeyCheckAuthority function i placed a condition to call itself after 1 second when gapi.client is null.
function SetKeyCheckAuthority() {
if(null == gapi.client) {
window.setTimeout(SetKeyCheckAuthority,1000);
return;
}
//set API key and check for authorization here }

Categories

Resources