JavaScript is known to be in the design of security considerations, is not allowed to read and write local files (reason please Baidu);
But in the actual project application, often uses to upload the picture, and lets the user preview the picture directly. For this approach there are two ways to achieve: first, the front and back of the interaction, the background image address back to the front;
Second, what I wrote today, using the filereader Object--Allows the Web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, which optimizes the image loading speed and reduces the bandwidth-consuming problem of the method;
However, there is a problem with this method compatibility, mainly IE browser (ie10 above no problem), this article does not discuss compatibility issues, the code is as follows:
<!DOCTYPE HTML><HTML> <Head> <MetaCharSet= "UTF-8"> <title></title> <Metaname= "Viewport"content= "Width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <styletype= "Text/css">#preview{Display:Inline-block;width:2.56rem;Height:2.56rem;position:relative;Background-image:URL (img/iconfont-tianjia.png);background-repeat:no-repeat;background-size:cover; }#file{width:100%;Height:100%;Opacity:0;position:Absolute; Left:0;Top:0;cursor:Pointer;Z-index:5; } </style> </Head> <Body> <DivID= "Preview"> <inputtype= "File"Accept= "image/*"ID= "File"value="" /> </Div> <Scripttype= "Text/javascript"> varPreview=Document.queryselector ('#preview'); varElefile=Document.queryselector ('#file'); Elefile.addeventlistener (' Change', function() { varfile= This. files[0]; //confirm that the selected file is a picture if(File.type.indexOf ("Image") == 0) { varReader= NewFileReader (); Reader.readasdataurl (file); Reader.onload= function(e) {//Picture Base64 varNewurl= This. Result; Preview.style.backgroundImage= 'URL (' +Newurl+ ')'; }; } }); </Script> </Body></HTML>
For direct multiplexing, thefilereader object is then displayed by converting the image URL into the base64 format.
Front End Implementation input[type= ' file ' upload picture preview effect