Ajax 上傳圖片并預(yù)覽的簡單實現(xiàn)
1. 直接上最簡單的 一種 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 {
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, 網(wǎng)上多得很。
以上就是小編為大家?guī)淼腁jax 上傳圖片并預(yù)覽的簡單實現(xiàn)的全部內(nèi)容了,希望對大家有所幫助,多多支持腳本之家~
相關(guān)文章
Jquery版本導(dǎo)致Ajax不執(zhí)行success回調(diào)函數(shù)
這篇文章主要介紹了Jquery Ajax不執(zhí)行success回調(diào)函數(shù)的原因及解決方法2014-04-04
Django框架利用ajax實現(xiàn)批量導(dǎo)入數(shù)據(jù)功能
這篇文章主要介紹了Django框架利用ajax實現(xiàn)批量導(dǎo)入數(shù)據(jù)功能的相關(guān)資料,需要的朋友可以參考下2016-03-03
關(guān)于Ajax異步請求后臺數(shù)據(jù)進(jìn)行動態(tài)分頁功能
這篇文章主要介紹了Ajax異步請求后臺數(shù)據(jù)進(jìn)行動態(tài)分頁功能,本文通過實例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2018-06-06
ajax回調(diào)函數(shù)中使用$(this)取不到對象的解決方法
如果在ajax的回調(diào)函數(shù)內(nèi)使用$(this)的話,實踐證明,是取不到任何對象的,需要的朋友可以參考下2014-06-06
Ajax返回數(shù)據(jù)之前的loading等待效果
我們通過ajax請求,向后臺傳遞參數(shù),然后后臺經(jīng)過一系列的運(yùn)算之后向前臺返還數(shù)據(jù),我希望在等待數(shù)據(jù)成功返還之前可以展示一個loading.gif圖。接下來通過本文給大家分享Ajax返回數(shù)據(jù)之前的loading等待效果,需要的朋友可以參考下2017-08-08

