How do I check if file exists in jQuery or pure JavaScript?

前端 未结 18 2085
闹比i
闹比i 2020-11-22 00:56

How do I check if a file on my server exists in jQuery or pure JavaScript?

18条回答
  •  天涯浪人
    2020-11-22 01:26

    Here's how to do it ES7 way, if you're using Babel transpiler or Typescript 2:

    async function isUrlFound(url) {
      try {
        const response = await fetch(url, {
          method: 'HEAD',
          cache: 'no-cache'
        });
    
        return response.status === 200;
    
      } catch(error) {
        // console.log(error);
        return false;
      }
    }
    

    Then inside your other async scope, you can easily check whether url exist:

    const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
    
    console.log(isValidUrl); // true || false
    

提交回复
热议问题