1. 直接上最簡(jiǎn)單的 一種 ajax 異步上傳圖片,并預(yù)覽
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 {
ListFileItem> 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. 這里會(huì) 用到一個(gè) ajaxupload.js, 網(wǎng)上多得很。
以上就是小編為大家?guī)?lái)的Ajax 上傳圖片并預(yù)覽的簡(jiǎn)單實(shí)現(xiàn)的全部?jī)?nèi)容了,希望對(duì)大家有所幫助,多多支持腳本之家~
您可能感興趣的文章:- jQuery AjaxUpload 上傳圖片代碼
- php+ajax無(wú)刷新上傳圖片實(shí)例代碼
- swfupload ajax無(wú)刷新上傳圖片實(shí)例代碼
- jquery的ajaxSubmit()異步上傳圖片并保存表單數(shù)據(jù)演示代碼
- JQuery+ajax實(shí)現(xiàn)批量上傳圖片(自寫)
- Jquery ajaxsubmit上傳圖片實(shí)現(xiàn)代碼
- AJAX實(shí)現(xiàn)圖片預(yù)覽與上傳及生成縮略圖的方法
- 基于HTML5的可預(yù)覽多圖片Ajax上傳
- 用ajax實(shí)現(xiàn)預(yù)覽鏈接可以看到鏈接的內(nèi)容
- Ajax上傳圖片及上傳前先預(yù)覽功能實(shí)例代碼