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 { 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ī)淼腁jax 上傳圖片并預(yù)覽的簡單實(shí)現(xiàn)的全部內(nèi)容了,希望對(duì)大家有所幫助,多多支持腳本之家~
標(biāo)簽:鄭州 舟山 邢臺(tái) 洛陽 林芝 內(nèi)蒙古 遼源 海南
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Ajax 上傳圖片并預(yù)覽的簡單實(shí)現(xiàn)》,本文關(guān)鍵詞 Ajax,上傳,圖片,并,預(yù)覽,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。