首页  >  文章  >  web前端  >  Ajax 上传图片并预览的简单实现

Ajax 上传图片并预览的简单实现

亚连
亚连原创
2018-05-23 14:30:041543浏览

下面我就为大家带来一篇Ajax 上传图片并预览的简单实现。现在就分享给大家,也给大家做个参考。

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();">
  
  <p class="images"></p>
  
<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 : &#39;upload.htm&#39;,
      fileElementId : &#39;images&#39;,
      dataType : &#39;json&#39;,
      data : {desc : $("#desc").val()},
      success : function(data) {
        var html = $(".images").html();
        html += &#39;<img width="100" height="100" src="/HotelManager/upload/&#39; + data.url + &#39;">&#39;
        $(".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();
    }
  }

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

基于ajax html实现文件上传技巧总结

在dom4j中使用XPath的简单实例

浅谈Bootstrap的DatePicker日期范围选择

以上是Ajax 上传图片并预览的简单实现的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn