Note that there are some explanatory texts on larger screens.

plurals
  1. PODetecting a file's content-type when using JavaScript's FileReader interface
    text
    copied!<p>I've been setting up an import script for plain-text files in a web application.</p> <p>My script is as follows:</p> <pre><code>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 &lt; 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) } } </code></pre> <p>It's essentially a modification of that posed on <a href="https://stackoverflow.com/questions/4100927/chrome-filereader">this question</a>.</p> <p>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.</p> <p>I've noticed in the console that the browser detects the content-type of the file being imported. Here's an example.</p> <pre><code>fileName: "ideas.txt" fileSize: 377 name: "ideas.txt" size: 377 type: "text/plain" webkitRelativePath: "" </code></pre> <p>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?</p> <p>Thanks in advance for any advice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload