Before the file upload, we always want to preview the contents of the file, or the image, HTML5 in the FileReader just provide 2 ways, you can not upload files in the case, preview the contents of the file.
Image preview: Readasdataurl (file);
File preview: Readastext (); (must ensure that the file encoding format is the same as the Code encoding format, preview Chinese will not garbled)
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>HTML5 Practice</title> <styletype= "Text/css"> </style></Head><Body> <inputtype= FileID= ' file '/> <inputtype= Buttononclick= ' readimg () 'value= ' Read image '/> <inputtype= Buttononclick= ' readFile () 'value= ' Read file '/> <DivID= ' result '></Div> <Scriptlanguage= ' JavaScript '> functionShowfilename () {varFiles=document.getElementById ('file'). files; varfile; for(varI= 0, Len=files.length; I<Len; I++) {file=Files[i]; Console.log (File.name); } } functionreadimg () {varfile=document.getElementById ('file'). files[0]; if(!/image\/\w+/. Test (File.type)) {Alert ("Make sure the file is of the image type! "); return false; } varReader= NewFileReader (); Reader.readasdataurl (file); Reader.onload= function(e) {varresult=document.getElementById ('result'); Result.innerhtml= ""+ This. Result+"' alt = '/>"; }; } functionReadFile () {varfile=document.getElementById ('file'). files[0]; varReader= NewFileReader (); Reader.readastext (file); Reader.onload= function(f) {varresult=document.getElementById ('result'); Result.innerhtml= This. Result; } } </Script></Body></HTML>
FileReader of the HTML5 file API