The thing that is going to be said is not new.
Reference: Reading files in JavaScript using the File APIs (given the author's presence in the United States, I would assume that the author's native language is English, of course there are localized in the link to choose Chinese)
What effect to do, that is, the page has a <input type= "file"/> After the user chooses the image to upload, the page displays the image that will be uploaded.
Previously, Ajax was required to upload the original image to the server, and after a successful response, a picture was added to the page. If users find that the upload is wrong, they need to delete the corresponding picture on the server.
Now, you can do this, first on the code:
Document.queryselector (' #upfile '). onchange =function(evt) {varFiles =Evt.target.files; for(vari = 0, F; f = files[i]; i++){ if(!f.type.match (' image.* '))Continue; varReader =NewFileReader (); Reader.onload= (function(thefile) {return function(e) {varimg = document.createelement (' img ')); Img.title=Thefile.name; IMG.SRC=E.target.result; Document.body.appendChild (IMG); //Where do you want to plug in?}}) (f); Reader.readasdataurl (f); } }
1Document.queryselector (' #upfile '). onchange =function () {2 varFileReader =NewFileReader ();3Filereader.onload =function(e) {4 if(Filereader.readystate = =filereader.done) {5 varimg = document.createelement (' img '));6IMG.SRC = This. Result;7Document.body.appendChild (IMG);//example is simply inserting the body8 }9 }Ten //load multiple files at once One vari = 0, src = This. Files; A Filereader.readasdataurl (Src[i]); -Filereader.onloadend =function () { -i++; the if(I <src.length) Filereader.readasdataurl (Src[i]); - } -}
I wrote it, and you don't look at it.
Reprint Please specify source: http://www.cnblogs.com/zaiyuzhong/p/reading-files-by-fileAPIs.html
Corresponding HTML node: <input type= "file" id= "Upfile" multiple/> (if you do not use multiple selection to remove multiple)
The key to this code is on the FileReader object being instantiated, FileReader includes four options to read the file asynchronously:
- Filereader.readasbinarystring (file| BLOB)//result will contain data in the form of a binary string
- Filereader.readastext (file| Blob, [encoding])//result will contain data in the form of a string, the encoding format default Utf-8, which can be specified by the encoding parameter
- Filereader.readasdataurl (file| BLOB)//result will contain data in the form of a data URL
- Filereader.readasarraybuffer (file| BLOB)//result will contain data in the form of Arraybuffer
After calling a method, there will be Onloadstart, OnProgress, onload, Onabort, onerror and Onloadend events.
How to preview a picture to be uploaded-using H5 's FILEAPI