Check if image exists on server using JavaScript?

前端 未结 12 733
抹茶落季
抹茶落季 2020-11-22 06:24

Using javascript is there a way to tell if a resource is available on the server? For instance I have images 1.jpg - 5.jpg loaded into the html page. I\'d like to call a Jav

相关标签:
12条回答
  • 2020-11-22 07:17

    You can use the basic way image preloaders work to test if an image exists.

    function checkImage(imageSrc, good, bad) {
        var img = new Image();
        img.onload = good; 
        img.onerror = bad;
        img.src = imageSrc;
    }
    
    checkImage("foo.gif", function(){ alert("good"); }, function(){ alert("bad"); } );
    

    JSFiddle

    0 讨论(0)
  • 2020-11-22 07:26

    You can do this with your axios by setting relative path to the corresponding images folder. I have done this for getting a json file. You can try the same method for an image file, you may refer these examples

    If you have already set an axios instance with baseurl as a server in different domain, you will have to use the full path of the static file server where you deploy the web application.

      axios.get('http://localhost:3000/assets/samplepic.png').then((response) => {
                console.log(response)
            }).catch((error) => {
                console.log(error)
            })
    

    If the image is found the response will be 200 and if not, it will be 404.

    Also, if the image file is present in assets folder inside src, you can do a require, get the path and do the above call with that path.

    var SampleImagePath = require('./assets/samplepic.png');
    axios.get(SampleImagePath).then(...)
    
    0 讨论(0)
  • 2020-11-22 07:27

    You may call this JS function to check if file exists on the Server:

    function doesFileExist(urlToFile)
    {
        var xhr = new XMLHttpRequest();
        xhr.open('HEAD', urlToFile, false);
        xhr.send();
    
        if (xhr.status == "404") {
            console.log("File doesn't exist");
            return false;
        } else {
            console.log("File exists");
            return true;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:27

    Basicaly a promisified version of @espascarello and @adeneo answers, with a fallback parameter:

    const getImageOrFallback = (path, fallback) => {
      return new Promise(resolve => {
        const img = new Image();
        img.src = path;
        img.onload = () => resolve(path);
        img.onerror = () => resolve(fallback);
      });
    };
    
    // Usage:
    
    const link = getImageOrFallback(
      'https://www.fillmurray.com/640/360',
      'https://via.placeholder.com/150'
      ).then(result => console.log(result) || result)
    
    // It can be also implemented using the async / await API.

    Note: I may personally like the fetch solution more, but it has a drawback – if your server is configured in a specific way, it can return 200 / 304, even if your file doesn't exist. This, on the other hand, will do the job.

    0 讨论(0)
  • 2020-11-22 07:27

    You can refer this link for check if a image file exists with JavaScript.

    checkImageExist.js:

        var image = new Image();
        var url_image = './ImageFolder/' + variable + '.jpg';
        image.src = url_image;
        if (image.width == 0) {
           return `<img src='./ImageFolder/defaultImage.jpg'>`;
        } else {
           return `<img src='./ImageFolder/`+variable+`.jpg'`;
        } } ```
    
    0 讨论(0)
  • This works fine:

    function checkImage(imageSrc) {
        var img = new Image();        
        try {
            img.src = imageSrc;
            return true;
        } catch(err) {
            return false;
        }    
    }
    
    0 讨论(0)
提交回复
热议问题