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上传图片并预览的简单实现的全部内容了,希望对大家有所帮助,多多支持毛票票~
热门推荐
2 成都训练狗狗
3 怎么训练小狗狗
4 训练狗狗软件
5 如何训练狗狗拉屎
9 狗狗负重训练
10 狗狗多大可以训练大小便
11 怎么训练狗狗萨摩耶
12 狗狗训练书
13 鞍山狗狗训练
14 训练狗狗用品
15 怎样才能训练狗狗听话
16 狗狗如何训练大小便
17 怎样训练狗狗睡狗窝
18 训练狗狗工具