Form表单:
<form action="" method="post" id="myform" name="myform" enctype="multipart/form-data"> <tr> <th><i class="require-red">*</i>图片:</th> <td> <p> <div id="imgs"></div> <input type="hidden" value="" id="hfImg" name="hfImg"> </p> <input type="file" name="pic" id="pic" multiple> </td> </tr> </form>
JS代码:
<script type="text/javascript"> $(function (){ $("#pic").change(function (){ var files=$("#pic")[0].files; for(var i=0;i<files.length;i++){ //files[i] File{name: '3.jfif', lastModified: 1663635088185, lastModifiedDate: Tue Sep 20 2022 08:51:28 GMT+0800 (中国标准时间), webkitRelativePath: '', size: 205489,…} var value=files[i].name; var index=value.lastIndexOf("."); var fileext=value.substring(index,value.length); if(".jpg.jpeg.png.gif.bmp.webp".indexOf(fileext)==-1){ alert("请上传.jpg .jpeg .png .gif .bmp .webp格式的图片"); return; } } //创建一个表单的对象 html对象 不能用ajax对象 var formData=new FormData($("#myform")[0]); $.ajax({ url:"${path}/manage/product?action=updatePic", type:"post", data:formData, async: false, // 设置为同步执行 contentType:false, //不让ajax指定上传的类型 application/x-www-form-urlencoded processData:false, //不让ajax处理上传的数据 success:function(data){ var pics=data.split(","); for(var i=0;i< pics.length;i++){ var img=$("<img>"); img.attr("src","${path}"+pics[i]); $("#imgs").append(img); } <%--$("#imgUrl").show();--%> <%--$("#imgUrl").attr("src","${path}"+"/"+data);--%> $("#hfImg").val(data); } }); }); }); </script>
Servlet代码:
private void updatePic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filenameStr=""; //获得上传的对象 Collection<Part> parts=request.getParts(); for(Part p:parts){ if(p.getName().equals("pic")){ String fileName=p.getSubmittedFileName(); if(fileName!=null&&fileName!=""){ System.out.println("==="+fileName); String fileext=fileName.substring(fileName.lastIndexOf(".")); String newFileName=UUID.randomUUID().toString().replace("-",""); String path=this.getServletContext().getRealPath("/")+"/img/"; p.write(path+newFileName+fileext); p.delete(); filenameStr+="/img/"+newFileName+fileext+","; } } } PrintWriter out=response.getWriter(); out.print(filenameStr.substring(0,filenameStr.length()-1)); out.close(); }
最终效果:
0条评论
点击登录参与评论