I want to open a file in Javascript that the user selects from the local filesystem. I can get the file name but I don't know how to open it.
<form action='' method='POST' enctype='multipart/form-data'>
<input id="archiveFile" type='file' name='userFile'><br>
<script>
archiveFile.onchange = function (e)
{
console.log(archiveFile.value);
// open the file here
}
</script>
</form>
You need for the HTML5 FileReader
Api, further information are there: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
here is a polyfill using Flash: https://github.com/Jahdrien/FileReader
This is a very well-made article: http://www.html5rocks.com/en/tutorials/file/dndfiles/#toc-reading-files it explains almost everything.
working example:
function FileReaderCtrl() { var self = this; var field = document.getElementById('fieldFile'); var result = document.getElementById('result'); self.readFile = function(event) { var res = event.target.result; var image = '<img src="'+ (res || '') +'"/>'; result.innerHTML = image; console.log(image); }; field.onchange = function(event) { var files = field.files; var reader; if(files.length < 1) { return; } reader = new FileReader(); reader.onload = self.readFile; reader.readAsDataURL(files[0]); } } document.addEventListener('DOMContentLoaded', FileReaderCtrl);
#result { width: 200px; height: 200px; background: lightcoral; margin: 1em auto; } img {max-width: 100% }
<label for="fieldFile">Select an Image:<br><input type="file" id="fieldFile"/></label> <div id="result"></div>
Substitute archiveFile.files
for archiveFile.value
. The value of an input type="file"
element is not a FileList
or File
object
For historical reasons, the
value
IDL attribute prefixes the file name with the string "C:\\fakepath\\"
archive.files
would be the FileList
object, from which you can iterate the selected File
object or objects if multiple
attribute is set at input type="file"
element. For example, archiveFile.files[0]
to view properties of individual File
object
<form action='' method='POST' enctype='multipart/form-data'> <input id="archiveFile" type='file' name='userFile'> <br> <script> archiveFile.onchange = function(e) { console.log(archiveFile.files, archiveFile.files[0]); // open the file here } </script> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.