Search code examples
angularjsionic-frameworkxmlhttprequesthttp-status-code-404

How to check if file exist locally and on a http server, and avoid 404 errors in the console


In my Angular/Ionic app, I have a big list of names, and I have to check if the corresponding image exists. Because sometimes we ship the image with the app, but sometimes we find the image later and we just put it on our server so we don't have to resubmit the app just for an image.

<ion-item collection-repeat="item in prodataSelect | orderBy:data.sort | filter: data.selectBrand.brand:true | filter: data.selectName.name | filter: generalSearchFunc | filterObj:['brand','modelStrict']" item-width="25%" item-height="35%" item-render-buffer="8">
    <a class="optionfuninit item-content">
        <div class="imagebox">
            <img class="imageoptionsmodel " ng-src="{{imagesUrls[item.imageName]}}" />
        </div>
    </a>
</ion-item>

I first check if the image exists locally (in the app), if not, I check if it exists on our server (http://...) and if not, I use a default image (default.png).

I check using this Angular service:

.service('UrlExists', [
            '$http',
            '$q',
            function ($http, $q) {
                'use strict';

                this.f = function (url) {
                    var http;
                    //UrlExistsDeferred = $q.defer();

                    try {
                        http = new XMLHttpRequest();
                        http.open("HEAD", url, false); //false is synchronous
                        http.send();
                    } catch (err) {
                        console.log("An error on the XMLHttpRequest:" + err.name + "---" + err.message);
                    }

                    if (http.readyState === 4) {
                        if (http.status === 200) {
                            //UrlExistsDeferred.resolve();
                            return true;
                        } else {
                            //UrlExistsDeferred.reject();
                            return  false;
                        }
                    }
                    //return UrlExistsDeferred.promise;
                };

But the issue is that I get a lot of 404 errors in the console, and it's very annoying.

Do you have a better idea?


Solution

  • Yes, I have a better idea. You could create an API function on the server which would take a URL post parameter, check if it exists on the server and return 1 if it exists and 0 if it does not exist. On client-side you could send POST requests to that API function, passing the URL(s) to be checked. Make sure you do not generate an error on the server if the file does not happen to exist.

    EDIT

    There are very good tutorials about creating RESTful APIs in PHP, therefore I will refrain from their detailed description and will just tell you that you will want some class which has some functions and you will want to be able to call the class's functions via reflection. When you are more-or-less done with implementing this, you will want to test it using PHP. Try to make sure that you will have a function which will take a string for method name and call the method based on that string. You will need that when the client-side will send commands. When you are done with testing the PHP part, you will have to implement the client-side usage. It is advisable to establish a communication where you could send messages like

    Check/IsURLExistent

    to the server and pass the URL as a POST parameter. However, always keep an eye on security, never allow things which might be dangerous. For instance if you create a function to remove pictures, then you will need to check whether the user has the necessary privileges to do so, as bad people will send POST messages to your API trying to steal data from you, or harm the integrity of your site.

    On the server-side you will need this functionality inside your class

    public function IsURLExistent($params) {
        return (file_exists($params["URL"]) ? 1 : 0);
    }
    

    and invoke this function. On client-side if you receive 1, then the file exists, if you receive 0, then it doesn't exist. You might want to check the path in the URL, to not allow programmers asking for file names at other places via the API function. Basically parts of things written in this answer are probably clear, other parts are probably unclear for your current level of knowlegde. However, if you take the time to study a few tutorials, linked here or even not linked here, then you will find the implementation of such an API very easy. Don't forget, this study will not be in vain, as it will greatly increase your status as a programmer.