1. 直接上最简单的 一种 ajax 异步上传图片,并预览
html:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>图片上传 | cookie</title>
</head>
<body>
file: <input type="file" id="images" name="image" /><br><br>
desc: <input type="text" id="desc" name="desc" /><br><br>
<input type="button" value="upload" onclick="upload();">
<div class="images"></div>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/upload.js"></script>
<script type="text/javascript">
function upload() {
$.ajaxfileupload({
url : 'upload.htm',
fileelementid : 'images',
datatype : 'json',
data : {desc : $("#desc").val()},
success : function(data) {
var html = $(".images").html();
html += '<img width="100" height="100" src="/hotelmanager/upload/' + data.url + '">'
$(".images").html(html);
}
})
return false;
}
</script>
</body>
</html>
servlet:
protected void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
diskfileitemfactory factory = new diskfileitemfactory();
servletfileupload upload = new servletfileupload(factory);
string path = request.getservletcontext().getrealpath("/upload");
string name = null;
try {
list<fileitem> items = upload.parserequest(request);
for (fileitem item : items) {
if(item.isformfield()){
system.out.println(item.getfieldname() + ": " + item.getstring());
} else {
name = item.getname();
item.write(new file(path,name));
}
}
printwriter out = response.getwriter();
out.print("{");
out.print("url:"" + name +""");
out.print("}");
} catch (exception e) {
e.printstacktrace();
}
}
2. 这里会 用到一个 ajaxupload.js, 网上多得很。
以上就是小编为大家带来的ajax 上传图片并预览的简单实现的全部内容了,希望对大家有所帮助,多多支持~
隔壁的老王哥是龟