0

I'm trying to make file uploader. I'm successfully uploading the file and reading with FileReader. The problem here is that I don't know how to get file extension if the extension isn't written in the filename for example image instead of image.png.

I didn't find any way or solution for this.

Any ideas?

Devmasta
  • 513
  • 2
  • 14
  • 38
  • *"if the extension isn't written in the filename "* - It's not clear to me what exactly you mean by this. Are you trying to remove the file extension from a file name? Something else? Can you elaborate? – David Jul 08 '19 at 11:42
  • 3
    If you only have the filename, there is no possibility to extract something that isn't there. – MauriceNino Jul 08 '19 at 11:42
  • It would be appreciated, that you'd list which solutions didn't work so that we don't need to spend time when suggesting some non-working solutions. In all cases you should do the file type check on the server too. – Teemu Jul 08 '19 at 11:42
  • What OS are you using? Maybe it is default Windows behavior to hide the file extension? – Naeem Khan Jul 08 '19 at 11:43
  • @David I'm trying to get the file extension if the extension isn't written in the filename. Not always the filename ends with the file extension. – Devmasta Jul 08 '19 at 11:44
  • @Devmasta: So you're trying to get the file extension from a file that doesn't *have* an extension? How exactly would that even be possible? If it doesn't have one then it doesn't have one. What's the actual problem you're trying to solve here? Why do you think you need information that doesn't exist? – David Jul 08 '19 at 11:46
  • 2
    I guess you need the MIME type of the file? – Teemu Jul 08 '19 at 11:47
  • 1
    Please provide a code example of your current (not working solution). It is easier to extend it or to get context. – Marc Jul 08 '19 at 11:48
  • @Teemu yes that. – Devmasta Jul 09 '19 at 12:39
  • But then the linked dup doesn't answer the question ... – Teemu Jul 09 '19 at 13:56

3 Answers3

1

I'm not sure I understand your question but try to look at this link.
I have tried it's example with a file with no extension in its name and it works. (of course its solution is a bit strange for me!) As it says it gets file mime type based on 'first 4 bytes of the file' and not the file name.

I hope it helps.

Pouria Moosavi
  • 662
  • 7
  • 22
  • 1
    I suppose this is what OP wants. A good answer would explain the principal of how to use the linked code, though. Anyway, @Devmasta, please read also [this answer](https://stackoverflow.com/a/4581362/1169519) before doing anything else. – Teemu Jul 08 '19 at 12:07
0

I am not sure. May be it will help you.

var file = fileYouWantToCheck; //store your file into the 'file' variable
var extension = file.type;
console.log(extension);

For more details you can visit the link: MDN web docs: File.type

Showrin Barua
  • 1,737
  • 1
  • 11
  • 22
0

You can write ajax call to php file that checks and returns the mimetype for this, Here is the php function for that.

mime_content_type

That is simple think you can do. or Here is the code I found that can read file mime type of uploaded file to help you out with the problem.

See: http://stackoverflow.com/a/29672957/1938889

JSFiddle Here

// Return the first few bytes of the file as a hex string
function getBLOBFileHeader(url, blob, callback) {
  var fileReader = new FileReader();
  fileReader.onloadend = function(e) {
    var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
    var header = "";
    for (var i = 0; i < arr.length; i++) {
      header += arr[i].toString(16);
    }
    callback(url, header);
  };
  fileReader.readAsArrayBuffer(blob);
}

function getRemoteFileHeader(url, callback) {
  var xhr = new XMLHttpRequest();
  // Bypass CORS for this demo - naughty, Drakes
  xhr.open('GET', '//cors-anywhere.herokuapp.com/' + url);
  xhr.responseType = "blob";
  xhr.onload = function() {
    callback(url, xhr.response);
  };
  xhr.onerror = function() {
    alert('A network error occurred!');
  };
  xhr.send();
}

function headerCallback(url, headerString) {
  printHeaderInfo(url, headerString);
}

function remoteCallback(url, blob) {
  printImage(blob);
  getBLOBFileHeader(url, blob, headerCallback);
}

function printImage(blob) {
  // Add this image to the document body for proof of GET success
  var fr = new FileReader();
  fr.onloadend = function() {
    $("hr").after($("<img>").attr("src", fr.result))
      .after($("<div>").text("Blob MIME type: " + blob.type));
  };
  fr.readAsDataURL(blob);
}

// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures
function mimeType(headerString) {
  switch (headerString) {
    case "89504e47":
      type = "image/png";
      break;
    case "47494638":
      type = "image/gif";
      break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
      type = "image/jpeg";
      break;
    default:
      type = "unknown";
      break;
  }
  return type;
}

function printHeaderInfo(url, headerString) {
  $("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))
    .after($("<div>").text("File header: 0x" + headerString))
    .after($("<div>").text(url));
}

/* Demo driver code */

var imageURLsArray = ["http://media2.giphy.com/media/8KrhxtEsrdhD2/giphy.gif", "http://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", "http://static.giantbomb.com/uploads/scale_small/0/316/520157-apple_logo_dec07.jpg"];

// Check for FileReader support
if (window.FileReader && window.Blob) {
  // Load all the remote images from the urls array
  for (var i = 0; i < imageURLsArray.length; i++) {
    getRemoteFileHeader(imageURLsArray[i], remoteCallback);
  }

  /* Handle local files */
  $("input").on('change', function(event) {
    var file = event.target.files[0];
    if (file.size >= 2 * 1024 * 1024) {
      alert("File size must be at most 2MB");
      return;
    }
    remoteCallback(escape(file.name), file);
  });

} else {
  // File and Blob are not supported
  $("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );
} 
img {
  max-height: 200px
}
div {
  height: 26px;
  font: Arial;
  font-size: 12pt
}
form {
  height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
  <input type="file" />
  <div>Choose an image to see its file signature.</div>
</form>
<hr/>
mohitesachin217
  • 451
  • 5
  • 14