0

I'm trying to get the current browser's MIME type for a file extension using JavaScript. The problem is, that I don't have a File-object coming from an input or drop operation.

I tried this without success:

var f = new File([''], 'test.xml');
console.log(f.type); // outputs "" but I expect anything like "application/xml" 

Background why I am asking this is that I have a whitelist of allowed extensions to upload. While dragging a file over a drop zone, I would like to indicate whether the files are ok to drop or not. While dragging, I get the MIME types of the files but not the file names. My idea is to generate a local array of MIME types based on the allowed file extensions for comparism. I don't want to maintain a list of mime types on my backend because MIME types does not seem to be concise and relyable across browsers / OS'es.

Update: See comment why this question is not a duplicate.

martinoss
  • 5,268
  • 2
  • 45
  • 53
  • In my case, I know the file extension so it should not be treated as duplicate IMO. ricky2002 gets an image array from document. I need to get the MIME type just of a plain file name. – martinoss Jun 08 '15 at 14:08
  • http://stackoverflow.com/questions/18299806/how-to-check-file-mime-type-with-javascript-before-upload ??? – JoshNaro Jun 08 '15 at 14:43
  • Unfortunately I don't have an input field... – martinoss Jun 08 '15 at 15:12
  • _"While dragging, I get the MIME types of the files but not the file names."_ Don't you mean the other way around? Also this is fairly easy to subvert; just change the file extension. If you need to detect what type of image a file actually is, use an image library to read the image's magic number. – Colonel Thirty Two Jun 08 '15 at 18:03
  • @colonel32 - No, the filename is not available until I drop the file. I want to color the dropzone red if I'm dragging something over the zone that is not whitelisted. Let's say I'm dragging a pdf file over the zone: I get "application/pdf" in the event but not the file name. With this information, I want to check, if the file type is whitelisted. Say "pdf" is whitelisted. I need to predict to which file extension the drop will turn to. So was my idea, to "ask chrome" initially for every extension, which MIME-Type is associated with this file type, so I can compare the MIME-Types. – martinoss Jun 08 '15 at 18:21

0 Answers0