开发者

how to retrieve file type using jquery

I have two textboxes. One is a normal textbox and another 'input type="file"'

when I click on the button 开发者_运维知识库I want a label to be updated with the textbox value and it's href pointing to whatever I have attached to the file type.

How can this be done using jquery.

Googled a lot but din't find any answer


I had to do this exact same thing the other day. Here's the jQuery code I ended up using...

$("#filUpload").change(function() {
  $("#hypViewLocalDoc").remove();
  var val = this.value.toLowerCase();

  if(val.length == 0) return;

  if(val.substring(val.length - 3) != "pdf") {
    alert("Only PDF Documents are Allowed");
    return;
  }

  var url = 'file:///' + encodeURI(val);
  $(this).after('<a id="hypViewLocalDoc" href="' + url + '" target="_blank">Open</a>');
});


Here's my solution, which works in less-recent Mozilla-based browsers, newer browsers that also support the W3C FileAPI standard, and bad browsers like IE that don't support any of that stuff.

var getMediaType = function (fileInput, fileIndex) {
  var fileName;
  if (!("files" in fileInput)) { // doesn't support standard or non-standard FileAPI
    fileName = fileInput.value;
    return guessMediaType(
             fileName.substr(fileName.lastIndexOf(".") + 1).toLowerCase()
           );
  }
  fileName  = = file.name || file.fileName; // FileAPI: name, non-standard: fileName
  var file  = fileInput.files.item(fileIndex || 0),
  mediaType = file.mediaType || // FileAPI way
              file.getAsDataURL()
                .split(",")[0]
                .substr("data:".length)
                .split(";")[0]; // non-standard way

  if (!mediaType || mediaType === "application/octet-stream") {
    mediaType = guessMediaType(
      fileName.substr(fileName.lastIndexOf(".") + 1).toLowerCase()
    );
  }

  return mediaType;
},

formatTests = {
    // Text/document formats
    "text/plain"            : /^(?:te?xt$|readme)$/, // txt, text, readme
    "text/html"             : /^html?$/, // html, htm
    "application/xhtml+xml" : /^xht(?:ml|l)?$/, // xhtml, xhtm, xht
    "application/xml"       : "xml",
    "text/rtf"              : "rtf",
    "application/pdf"       : "pdf",
    "application/x-shockwave-flash" : "swf", // no idea where this would go

    // Image formats
    "image/png"      : /^a?png$/, // png, apng
    "image/jpeg"     : /^jpe?g$/, // jpeg, jpg
    "image/gif"      : "gif",
    "image/svg+xml"  : /^svgz?$/, // svg, svgz
    "image/x-ms-bmp" : /^(?:bmp|dib)$/, // bmp, dib
    "image/xbm"      : "xbm",
    "image/vnd.microsoft.icon" : "ico",

    // Video formats
    "video/ogg"        : "ogv",
    "video/mp4"        : /^(?:mp4|m4v|f4[vp])$/, // mp4, m4v, f4v, f4p
    "video/x-flv"      : "flv",
    "video/divx"       : "divx",
    "video/x-matroska" : /^mk[vas]$/, // mkv, mka, mks
    "video/3gpp"       : "3gp",
    "video/3gpp2"      : "3g2",

    // Audio formats
    "audio/ogg"     : /^og[ga]$/, // ogg, oga
    "audio/x-flac"  : "flac",
    "audio/x-speex" : "spx",
    "audio/mp4"     : /^(?:m4a|f4[ab])$/, // m4a, f4a, f4b

    // OpenDocument formats
    "application/vnd.oasis.opendoc.text" : "odt",
    "application/vnd.oasis.opendoc.presentation" : "odp",
    "application/vnd.oasis.opendoc.spreadsheet" : "ods",
    "application/vnd.oasis.opendoc.graphics" : "odg",

    // Microsoft formats
    "application/msword" : /^do[ct]$/, // doc, dot
    "application/vnd.ms-excel" : /^xl[tas]$/, // xlt, xla, xls
    "application/vnd.ms-powerpoint" : /^p(?:p[tsa]|ot)$/, // ppt, pot, pps, ppa
    "application/vnd.openxmlformats-officedoc.wordprocessingml.document" : /^doc[xm]$/, // docx, docm
    "application/vnd.openxmlformats-officedoc.presentationml.presentation" : "pptx",
    "application/vnd.openxmlformats-officedoc.spreadsheetml.sheet" : "xlsx",
    "application/vnd.openxmlformats-officedoc.wordprocessingml.template" : "dotx",
    "application/vnd.openxmlformats-officedoc.spreadsheetml.template" : "xltx",
    "application/vnd.openxmlformats-officedoc.presentationml.template" : "potx",
    "application/vnd.openxmlformats-officedoc.presentationml.slideshow" : "ppsx"

},

formats = [],

guessMediaType = function (ext) {
    var guessedType = "application/octet-stream",
    i = formats.length, test;
    while (i--) {
        test = formatTests[formats[i]];
        if ((typeof test === "string" && ext === test) ||
            (test instanceof RegExp && test.test(ext)))
        {
            guessedType = formats[i];
            break;
        }
    }
    return guessedType;
};

for (formatTest in formatTests) {
    if (formatTests.hasOwnProperty(formatTest)) {
        formats.unshift(formatTest);
    }
}

Use it as such:

getMediaType(document.getElementById("myFileInput"));

If you want to support multiple files, it also supports a second, fileIndex, argument.

Edit: Is your intention anything similar to having a graphic for the file type? If so, you can just do (Mozilla browsers-only) <img src="moz-icon://value of file input here?size=16" />. The only sizes supported are 16 and 32. For example:

var fileInput = document.getElementById("myFileInput"),
fileTypeIcon  = new Image();
fileTypeIcon.src = "moz-icon://" + fileInput.value + "?size=16";
// now append fileTypeIcon to any element in the document
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜