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

发布时间:2022-04-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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();">
  
  <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 上传图片并预览的简单实现的全部内容了,希望对大家有所帮助,多多支持脚本宝典~

脚本宝典总结

以上是脚本宝典为你收集整理的Ajax 上传图片并预览的简单实现全部内容,希望文章能够帮你解决Ajax 上传图片并预览的简单实现所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: