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?

10
  • "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? Commented Jul 8, 2019 at 11:42
  • 3
    If you only have the filename, there is no possibility to extract something that isn't there. Commented Jul 8, 2019 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. Commented Jul 8, 2019 at 11:42
  • 2
    I guess you need the MIME type of the file? Commented Jul 8, 2019 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. Commented Jul 8, 2019 at 11:48

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 before doing anything else.
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

1 Comment

This only works when file has extension is in its name, otherwise returns empty string.
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/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.