码迷,mamicode.com
首页 > Web开发 > 详细

Ajax 上传图片并预览

时间:2016-09-21 01:34:07      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

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, 网上多得很,实在找不到,也可以私我,给你们

Ajax 上传图片并预览

标签:

原文地址:http://www.cnblogs.com/javatochen/p/5891180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!