Ajax 上传图片并预览的简单实现
1.直接上最简单的一种ajax异步上传图片,并预览
html:
<!DOCTYPEhtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <title>图片上传|cookie</title> </head> <body> file:<inputtype="file"id="images"name="image"/><br><br> desc:<inputtype="text"id="desc"name="desc"/><br><br> <inputtype="button"value="upload"onclick="upload();"> <divclass="images"></div> <scripttype="text/javascript"src="js/jquery-1.12.4.min.js"></script> <scripttype="text/javascript"src="js/upload.js"></script> <scripttype="text/javascript"> functionupload(){ $.ajaxFileUpload({ url:'upload.htm', fileElementId:'images', dataType:'json', data:{desc:$("#desc").val()}, success:function(data){ varhtml=$(".images").html(); html+='<imgwidth="100"height="100"src="/HotelManager/upload/'+data.url+'">' $(".images").html(html); } }) returnfalse; } </script> </body> </html>
servlet:
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ DiskFileItemFactoryfactory=newDiskFileItemFactory(); ServletFileUploadupload=newServletFileUpload(factory); Stringpath=request.getServletContext().getRealPath("/upload"); Stringname=null; try{ List<FileItem>items=upload.parseRequest(request); for(FileItemitem:items){ if(item.isFormField()){ System.out.println(item.getFieldName()+":"+item.getString()); }else{ name=item.getName(); item.write(newFile(path,name)); } } PrintWriterout=response.getWriter(); out.print("{"); out.print("url:\""+name+"\""); out.print("}"); }catch(Exceptione){ e.printStackTrace(); } }
2.这里会用到一个ajaxupload.js,网上多得很。
以上就是小编为大家带来的Ajax上传图片并预览的简单实现的全部内容了,希望对大家有所帮助,多多支持毛票票~