Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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("Are you sure you want to import the selected file? This will overwrite any data that is currently saved in the application workspace.");
    for (i = 0; i < files.length; i++) {
        file = files[i]
        console.log(file)
        var reader = new FileReader()
        ret = []
        reader.onload = function(e) {
            window.localStorage.setItem("ApplicationData", e.target.result);
        }
        reader.onerror = function(stuff) {
            console.log("error", stuff)
            console.log (stuff.getMessage())
        }
        reader.readAsText(file)
    }
}

It's essentially a modification of that posed on this question.

However, at the moment the user can technically attempt to import any file. As it's designed for plain-text files, problems can arise if a different type of file is imported.

I've noticed in the console that the browser detects the content-type of the file being imported. Here's an example.

fileName: "ideas.txt"
fileSize: 377
name: "ideas.txt"
size: 377
type: "text/plain"
webkitRelativePath: ""

Is it possible, then, to set up an argument where the script detects the content-type of the file, and if it isn't one of a number of specified suitable content-types, have the script refuse to import it?

Thanks in advance for any advice.

like image 874
木川 炎星 Avatar asked Nov 24 '10 07:11

木川 炎星


People also ask

What does FileReader do in JavaScript?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

What is reader onload?

The FileReader. onload property contains an event handler executed when the load event is fired, when content read with readAsArrayBuffer, readAsBinaryString, readAsDataURL or readAsText is available.

What is file type in JS?

JS (JavaScript) are files that contain JavaScript code for execution on web pages. JavaScript files are stored with the . js extension.


1 Answers

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
}
like image 110
trembl Avatar answered Oct 21 '22 22:10

trembl