Ajax 上傳圖片並預覽

來源:互聯網
上載者:User

標籤:

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 上傳圖片並預覽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.