How do I check if a file on my server exists in jQuery or pure JavaScript?
问题:
回答1:
With jQuery:
$.ajax({ url:'http://www.example.com/somefile.ext', type:'HEAD', error: function() { //file not exists }, success: function() { //file exists } });
EDIT:
Here is the code for checking 404 status, without using jQuery
function UrlExists(url) { var http = new XMLHttpRequest(); http.open('HEAD', url, false); http.send(); return http.status!=404; }
Small changes and it could check for status HTTP status code 200 (success), instead.
回答2:
A similar and more up-to-date approach.
$.get(url) .done(function() { // exists code }).fail(function() { // not exists code })
回答3:
This works for me:
function ImageExist(url) { var img = new Image(); img.src = url; return img.height != 0; }
回答4:
i used this script to add alternative image
function imgError() { alert('The image could not be loaded.'); }
HTML:

回答5:
So long as you're testing files on the same domain this should work:
function fileExists(url) { if(url){ var req = new XMLHttpRequest(); req.open('GET', url, false); req.send(); return req.status==200; } else { return false; } }
Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file. If the file is big enough this method can take a while to complete.
The better way to do this would be changing this line: req.open('GET', url, false);
to req.open('HEAD', url, false);
回答6:
I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:
function UrlExists(url) { $('
').load(function() { return true; }).bind('error', function() { return false; }); }
It seems to work great, hope this helps someone!
回答7:
I use this script to check if a file exists (also it handles the cross origin issue):
$.ajax(url, { method: 'GET', dataType: 'jsonp' }) .done(function(response) { // exists code }).fail(function(response) { // doesnt exist })
Note that the following syntax error is thrown when the file being checked doesn't contain JSON.
Uncaught SyntaxError: Unexpected token
回答8:
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
回答9:
For a client computer this can be achieved by:
try { var myObject, f; myObject = new ActiveXObject("Scripting.FileSystemObject"); f = myObject.GetFile("C:\\img.txt"); f.Move("E:\\jarvis\\Images\\"); } catch(err) { alert("file does not exist") }
This is my program to transfer a file to a specific location and shows alert if it does not exist
回答10:
First creates the function
$.UrlExists = function(url) { var http = new XMLHttpRequest(); http.open('HEAD', url, false); http.send(); return http.status!=404; }
After using the function as follows
if($.UrlExists("urlimg")){ foto = "img1.jpg"; }else{ foto = "img2.jpg"; } $('
').attr('src',foto);
回答11:
What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.
What type of server are you trying to communicate with? You may need to write a small service to respond to the request.
回答12:
This doesn't address the OP's question, but for anyone who is returning results from a database: here's a simple method I used.
If the user didn't upload an avatar the avatar
field would be NULL
, so I'd insert a default avatar image from the img
directory.
function getAvatar(avatar) { if(avatar == null) { return '/img/avatar.jpg'; } else { return '/avi/' + avatar; } }
then

回答13:
JavaScript function to check if a file exists:
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; } }
回答14:
It works for me, use iframe to ignore browsers show GET error message
var imgFrame = $(''); if ($(imgFrame).find('img').attr('width') > 0) { // do something } else { // do something }
回答15:
An async call to see if a file exists is the better approach, because it doesn't degrade the user experience by waiting for a response from the server. If you make a call to .open
with the third parameter set to false (as in many examples above, for example http.open('HEAD', url, false);
), this is a synchronous call, and you get a warning in the browser console.
A better approach is:
function fetchStatus( address ) { var client = new XMLHttpRequest(); client.onload = function() { // in case of network errors this might not give reliable results returnStatus( this.status ); } client.open( "HEAD", address, true ); client.send(); } function returnStatus( status ) { if ( status === 200 ) { console.log( 'file exists!' ); } else { console.log( 'file does not exist! status: ' + status ); } }
source: https://xhr.spec.whatwg.org/
回答16:
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"); } });
回答17:
$ajax method work while js method does not work.