首页 > web前端 > js教程 > 正文

Ajax上传并预览图片(附代码)

php中世界最好的语言
发布: 2018-04-03 15:11:39
原创
2194 人浏览过

这次给大家带来Ajax上传并预览图片(附代码),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 : '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/&#39; + data.url + &#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();
    }
  }
登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax怎样提交form表单与实现文件上传

ajax后台success上传的json数据如何处理

以上是Ajax上传并预览图片(附代码)的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!