Detecting a file's content-type when using JavaScript's FileReader interface

后端 未结 2 1648
无人及你
无人及你 2021-01-02 11:51

I\'ve been setting up an import script for plain-text files in a web application.

My script is as follows:

function dataImport(files) {
    confirm(\         


        
相关标签:
2条回答
  • 2021-01-02 11:54

    The Content Type can be read with the following code:

    // Note: File is a file object than can be read by the HTML5 FileReader API
    var reader = new FileReader();
    
    reader.onload = function(event) {
      var dataURL = event.target.result;
      var mimeType = dataURL.split(",")[0].split(":")[1].split(";")[0];
      alert(mimeType);
    };
    
    reader.readAsDataURL(file);
    
    0 讨论(0)
  • 2021-01-02 11:58
    if (file.type.match('text/plain')) {
        // file type is text/plain
    } else {
        // file type is not text/plain
    }
    

    String.match is a RegEx, so if you would want to check, if the file is any type of text, you could do that:

    if (file.type.match('text.*')) {
        // file type starts with text
    } else {
        // file type does not start with text
    }
    
    0 讨论(0)
提交回复
热议问题