In the front-end development, in order to better user experience, in the image upload will first display the picture to the page and then click the Save button to complete the Upload Success Code section of the image to refer to other people's wording.
HTML code:
<div id="Myphoto"v-show="Personalphoto"> <divclass="Viewphoto"> ""alt=""Id="Portrait"style="width:300px;height:300px"/> </div> <divclass="ListBox"> <dl> <dt> please upload image </dt> <dd> <input type="file"Id="SaveImage"Name="Myphoto"> </dd> </dl> </div> <divclass="Save"> <input type="Button"Value="Save Picture"@click ="Imagesubmit"> </div> </div>
JS Code:
//display the picture in real time on the pageGreat () {document.getElementById ('SaveImage'). onchange =function () {varImgfile = This. files[0]; //this.file = event.target.files[0]; varFR =NewFileReader (); Fr.onload=function () {document.getElementById ('Portrait'). src =Fr.result; }; Fr.readasdataurl (Imgfile); } },
The JS Code section explains: Because it is a function declared in the methods method of Vue, it is also necessary to mount the method using This.great () in the mounted method.
Image upload part of the JS code:
Imagesubmit () {Let x= document.getElementById ('SaveImage'). files[0]; Console.log (x); Letparams=NewFormData ();//Create a Form object params. Append ('file', x,x.name);//append adding data to a form form//Add a request header the format of the pictures and files that are added through the form must be Multipart/form-dataLet config ={headers:{'Content-type':'Multipart/form-data'} }; This. $axios. Post ("/user/image",params, config). Then (function (res) {Console.log (res); This. Imagesave =Res.data.image; Sessionstorage.setitem ('headimg', This. Imagesave);//Save the picture and be able to load the display somewhere elseRouter.go (0);//Refresh page, avatar change}.bind ( This)) .Catch(function (Error) {Console.log (error); }) } },
Note: In the later development process, it was found that uploading images can be used in the page loading before uploading the server.
var windowurl = window. URL | | Window.webkiturl;
Use Axios post to upload avatar/Picture in Vue and display it to the page in real time