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" /><br><br> desc: <input type="text" /><br><br> <input type="button" value="upload"> <div></div> <script type="text/javascript" src="https://www.jb51.net/js/jquery-1.12.4.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/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 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 上传图片并预览的简单实现的全部内容了,希望对大家有所帮助,多多支持脚本之家~

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjpgyd.html