developer tip

JavaScript를 사용하여 이미지가 서버에 있는지 확인 하시겠습니까?

optionbox 2020. 8. 6. 08:16
반응형

JavaScript를 사용하여 이미지가 서버에 있는지 확인 하시겠습니까?


자바 스크립트를 사용하여 서버에서 리소스를 사용할 수 있는지 알 수있는 방법이 있습니까? 예를 들어 html 페이지에 이미지 1.jpg-5.jpg 가로 드되어 있습니다. 매분마다 JavaScript 함수를 호출하여 대략 다음 스크래치 코드를 수행하고 싶습니다 ...

if "../imgs/6.jpg" exists:
    var nImg = document.createElement("img6");
    nImg.src = "../imgs/6.jpg";

생각? 감사!


다음과 같은 것을 사용할 수 있습니다.

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

분명히 jQuery / similar를 사용하여 HTTP 요청을 수행 할 수 있습니다.

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })

이미지 프리 로더가 작동하는 기본 방식을 사용하여 이미지가 있는지 테스트 할 수 있습니다.

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


모든 이미지에 제공되는 내장 이벤트를 사용하여 이미지가로드되는지 여부를 확인할 수 있습니다.

onloadonerror이미지가 성공적으로로드하는 경우 또는 오류가 발생하면 이벤트가 당신을 말할 것이다 :

var image = new Image();

image.onload = function() {
    // image exists and is loaded
    document.body.appendChild(image);
}
image.onerror = function() {
    // image did not load

    var err = new Image();
    err.src = '/error.png';

    document.body.appendChild(err);
}

image.src = "../imgs/6.jpg";

If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here

getInitialState: function(event) {
    return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
    this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
    return (
        <img onError={this.handleError} src={src} />;
    );
}

If you create an image tag and add it to the DOM, either its onload or onerror event should fire. If onerror fires, the image doesn't exist on the server.


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;
    }
}

This works fine:

function checkImage(imageSrc) {
    var img = new Image();        
    try {
        img.src = imageSrc;
        return true;
    } catch(err) {
        return false;
    }    
}

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(...)

A better and modern approach is to use ES6 Fetch API to check if an image exists or not:

fetch('https://via.placeholder.com/150', { method: 'HEAD' })
    .then(res => {
        if (res.ok) {
            console.log('Image exists.');
        } else {
            console.log('Image does not exist.');
        }
    }).catch(err => console.log('Error:', err));

Make sure you are either making the same-origin requests or CORS is enabled on the server.


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.

참고URL : https://stackoverflow.com/questions/18837735/check-if-image-exists-on-server-using-javascript

반응형