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

前端 未结 18 2476
闹比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:40

    This is an adaptation to the accepted answer, but I couldn't get what I needed from the answer, and had to test this worked as it was a hunch, so i'm putting my solution up here.

    We needed to verify a local file existed, and only allow the file (a PDF) to open if it existed. If you omit the URL of the website, the browser will automatically determine the host name - making it work in localhost and on the server:

    $.ajax({
    
        url: 'YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf',
        type: 'HEAD',
        error: function () {
            //file not exists
            alert('PDF does not exist');
    
        },
        success: function () {
            //file exists
            window.open('YourFolderOnWebsite/' + SomeDynamicVariable + '.pdf', "_blank", "fullscreen=yes");
    
        }
    });
    

提交回复
热议问题