Scene: The user clicks the picture to eject the upload file the frame, then selects will replace the picture, selects after the real-time preview, clicks is ok to upload through the Ajax to the server.
Front-End HTML
<div id= "Img_div" >
<input type= "file" id= "Img_upload" >
</div>
set the transparency of the upload INPUT element in the HTML above to 0, and set the width and height to cover a tag, and note that the position of the external div is set .
#img_div {
position:relative;
}
#img_upload {
opacity:0;
Position:absolute;
top:0;
left:0;
width:100%;
Z-index:9;
height:100%;
}
JS Code
Set up real-time preview listener
function Setonchangelistener () {
$ ("body") for Avatar Upload. On ("Change", "#img_upload", Previewfile)
;
Real-time preview upload picture
function Previewfile () {
var preview=$ ("#picture");
var file=$ ("#img_upload") [0].files[0];
var reader=new filereader ();
Reader.addeventlistener ("Load", function () {
preview.prop ("src", reader.result);
},false);
if (file) {
reader.readasdataurl (file);
}
}
Upload picture
function setpicture () {
var file=$ ("#img_upload") [0].files[0];
if (file==null) return
;
var formdata=new formData ();
Formdata.append (' file ', file);
var url=serverurl+ "Uploadpic";
$.ajax ({
url:url,
type: ' POST ',
cache:false,
data:formdata,
processdata:false,
Contenttype:false,
xhrfields: {
withcredentials:true
},
crossdomain:true,
});
which
Processdata:false,
Contenttype:false,
the settings need to be noted.
In the background I use the Java Web (SPRINGMVC) to paste the controller to receive the uploaded file code
@RequestMapping ("/uploadpic") public
@ResponseBody Object handleuploadpic (@RequestParam ("file") Multipartfile file, HttpServletRequest request) {
String username=cookieservice.getusername (request);
String picurl=fileservice.saveimg (file);
String Oldpicurl=manageservice.getpicurl (userName);
Fileservice.deletefile (Oldpicurl);
Manageservice.setpicurl (Username,picurl);
Map<string,object> result=new hashmap<string, object> ();
Result.put (Keystatus,valuestatusok);
return result;
}
Where file is the uploaded files received