Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining unknown content-types with the Html5 file api

I'm working through a small file upload script (learning experience) and I noticed that when selecting microsoft office related files (.doc or .docx for example) the file objects do not have a type specified:

filelist

For .doc files I had expected the type to be "application/msword" and along the same train of thought .docx to be "application/vnd.openxmlformats-officedocument.wordprocessingml.document".

In the cases when the type cannot be determined is the correct course of action to look at the file extension and match that to the "expected" content / mime type?

Sample script:

<div id="fileUpload">
    <input type="file" id="fileElem" style="display:none;" onchange="handleFiles(this.files)"/>
    <a href="#" id="fileSelect">Select some files</a>
</div>

<script type="text/javascript">
    var fileSelect = document.getElementById("fileSelect"),
        fileElem = document.getElementById("fileElem");

    fileSelect.addEventListener("click", function (e) {

        if (fileElem) {
            fileElem.click();
        }

        e.preventDefault();
    }, false);

    function handleFiles(files) {
        console.log(files);
    }

</script>
like image 348
Jesse Avatar asked Jun 25 '12 02:06

Jesse


1 Answers

According to the W3 File Api Draft the type attributte:

The ASCII-encoded string in lower case representing the media type of the Blob, expressed as an RFC2046 MIME type [RFC2046]. On getting, conforming user agents SHOULD return the MIME type of the Blob, if it is known. If conforming user agents cannot determine the media type of the Blob, they MUST return the empty string. A string is a valid MIME type if it matches the media-type token defined in section 3.7 "Media Types" of RFC 2616

So basically, if it's not a valid or media-type of HTTP/1.1 it will be empty. Anyways.

Yeah, you should do something like:

if(type === "") {
  //Get extension and match to a MIME-types list. (http://www.htmlquick.com/es/reference/mime-types.html)
}
like image 58
Bruno Avatar answered Nov 07 '22 06:11

Bruno