标签:
1. 直接上最简单的 一种 ajax 异步上传图片,并预览
html:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>图片上传 | cookie</title> 6 </head> 7 <body> 8 file: <input type="file" id="images" name="image" /><br><br> 9 desc: <input type="text" id="desc" name="desc" /><br><br> 10 <input type="button" value="upload" onclick="upload();"> 11 12 <div class="images"></div> 13 14 <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> 15 <script type="text/javascript" src="js/upload.js"></script> 16 <script type="text/javascript"> 17 function upload() { 18 $.ajaxFileUpload({ 19 url : ‘upload.htm‘, 20 fileElementId : ‘images‘, 21 dataType : ‘json‘, 22 data : {desc : $("#desc").val()}, 23 success : function(data) { 24 var html = $(".images").html(); 25 html += ‘<img width="100" height="100" src="/HotelManager/upload/‘ + data.url + ‘">‘ 26 $(".images").html(html); 27 } 28 }) 29 return false; 30 } 31 </script> 32 </body> 33 </html>
servlet:
1 protected void doPost(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 DiskFileItemFactory factory = new DiskFileItemFactory(); 4 5 ServletFileUpload upload = new ServletFileUpload(factory); 6 7 String path = request.getServletContext().getRealPath("/upload"); 8 String name = null; 9 try { 10 List<FileItem> items = upload.parseRequest(request); 11 for (FileItem item : items) { 12 if(item.isFormField()){ 13 System.out.println(item.getFieldName() + ": " + item.getString()); 14 } else { 15 name = item.getName(); 16 item.write(new File(path,name)); 17 } 18 } 19 PrintWriter out = response.getWriter(); 20 out.print("{"); 21 out.print("url:\"" + name +"\""); 22 out.print("}"); 23 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } 27 }
3. 这里会 用到一个 ajaxupload.js, 网上多得很,实在找不到,也可以私我,给你们
标签:
原文地址:http://www.cnblogs.com/javatochen/p/5891180.html