0

I have a js program in which I would like to build a link to a file in a specific directory. However, the js program does not know if the file will be .html, .xls .doc or .docx or others. All it knows is the directory and the first part of the filename. I have control of that directory and there will only be one file there with that first part.

Is there anyway to do this?

  • So if I understand you, all you have is 1.) Directory and 2.) File name? So of `/path/to/file.txt` all you have is `/path/to/file`, yes? – mattsven Feb 09 '14 at 23:53
  • What I am trying to get is the file name for a specific event (the date of which I know and there is only one event on any one day) where the results of the event are always in /path/Results/yyyymmdd_results.?. Sometimes the results are an excel file, sometimes an html format and sometimes a doc file. Hope that helps. – Lorna Guttormson Feb 09 '14 at 23:59

3 Answers3

2

No. You can try these different file endings and check if the server returns something or a 404 instead. Otherwise you have the implement some logic on the server to check the directory.

Tilman Schweitzer
  • 1,437
  • 10
  • 10
0

Only with javascript you can't access any files because security reasons reference here, but you can create an ActiveX for Internet Explorer only.

Community
  • 1
  • 1
djluis
  • 362
  • 5
  • 19
  • Thanks all I was afraid that was the answer. I guess I go to plan B - ensure I have an html file every time even if it just gives a link to the correct file. (80% of the time it is an html). Folks will just have to click once more. – Lorna Guttormson Feb 10 '14 at 00:04
0

This is not a good practice and I am not recommending it, but sure it can be done: Live demo (click).

//list each file name you want to find
var files = ['some-file', 'some-other-file'];

//list possible extensions
var exts = ['html', 'doc'];

//iterate each file name
$.each(files, function(index, file) {
  //attempt to get the file
  //pass a copy of the "exts" array so that each function can "shift" through it
  getFile(file, exts.slice());
});

function getFile(file, exts) {
  //the filename to try (added extension)
  var newFile = file+'.'+exts.shift();
  //try to get the file
  $.get(newFile).then(function(data) {
    //found the file - do something with the contents
    foo(data);
  }, function() {
    //file not found
    //if there are any extensions left to try
    if (exts.length) {
      //try again (will shift to next extension)
      getFile(file, exts);
    }
  });
}

function foo(data) {
  var div = document.createElement('div');
  div.textContent = data;
  document.body.appendChild(div);
}
m59
  • 43,214
  • 14
  • 119
  • 136