Ajax 上傳圖片並預覽的簡單實現_AJAX相關

來源:互聯網
上載者:User

1. 直接上最簡單的 一種 ajax 非同步上傳圖片,並預覽

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, 網上多得很。

以上就是小編為大家帶來的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.