利用ajax与springmvc传送formdata实现图片的无刷新上传

来源:互联网 发布:开源cms投资 编辑:程序博客网 时间:2024/05/29 03:39


<form id="frm_identityA" action="" enctype="multipart/form-data"> 
     <span style="display:none">  
      
      <input type="file" id="identityA" name="identityA" value=""> 
     </span> 
    </form>


  <div style="margin-top:10px;margin-left:20px">
     <--这是图片点击就上传-->
     <img type="button" id="button_identityA" src="<%=request.getContextPath() %>/resources/static/images/a.png" alt="" name="img_identityA"/>
     </div>
   
     <div style=" width:150px;height:150px; margin-left:350px"  >
      <--这是上传图片的位置-->
      <img  path="img"  id="img_identityA" src="" alt="" name="aaa"/>




<script type="text/javascript">
    
    
    // 点击按钮的时候选择图片
   
     $("#button_identityA").click(function() {
      $("#identityA").click();
     });
     // input框改变的时候将图片发送给后台
     $("#identityA")
       .change(
         function() {
          
       
          var formData = new FormData(
            $("#frm_identityA")[0]);
         
          
            $.ajax({
             url : "<%=request.getContextPath() %>/admin/account/upload",
             // 自行按需配置好完整的url,包括ip和端口号 
             
             type : "POST",
             data : formData,
             
             async : false,
             cache : false,
             contentType : false,
             processData : false,
             
             error: function() {
              alert("error");
              
              $("#img_identityA")
                .attr("src",
                  "<%=request.getContextPath() %>/resources/img/b.png");
             },
             success : function(
               returndata) {
              alert("success");
             
              $("#img_identityA")
                .attr(
                  "src",
                  "<%=request.getContextPath() %>/admin/account/showImages?name=identityA&"
                    + new Date()
                      .toTimeString());
              $("#img_identityA")
                .attr("width",
                  "124");
              $("#img_identityA")
                .attr("height",
                  "124");
             },
             
            });
         });
     
     </script>


java  中的control

 /**
         * 存放上传的图片信息
         */
        private static Map<String,byte[]> images; 
         
         static { 
                 images = new HashMap<String, byte[]>(); 
            } 


1、图片上传

  @RequestMapping(value = "upload", method = RequestMethod.POST)
      public String upLoad(HttpServletRequest request,HttpServletResponse response,HttpSession session) { 
             // 从请求中获取到文件信息需要将请求转换为MultipartHttpServletRequest类型 
              MultipartHttpServletRequest MulRequest = request instanceof MultipartHttpServletRequest ? (MultipartHttpServletRequest) request : null; 
           
              System.out.println("怎么回事");
              Iterator<String> fileNames = MulRequest.getFileNames(); 
              if (fileNames.hasNext()) { // 遍历请求中的图片信息 
                  String fileName = fileNames.next(); // 图片对应的参数名 
                  
                  MultipartFile    file = MulRequest.getFile(fileName); // 获取到图片 
                  if (file != null) { 
                      
                      try {
                       
                       byte[] data=file.getBytes();// 可以获取到图片的字节数组
           images.put(fileName,file.getBytes());// 获取到图片以字节数组形式保存在服务器内存中
           
           SimpleDateFormat sdf = new SimpleDateFormat("ddHHmmss");
            Login  lo =(Login)session.getAttribute("loginUser");
            
            String userid=lo.getUserID();
           
           String pictime =sdf.format(new Date());
           session.setAttribute("pictime", pictime);
           
           FileOutputStream fileOutputStream=new FileOutputStream("D:\\"+userid+pictime+".jpg");
           
           
           fileOutputStream.write(data);
           
           
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
                     
                      return  null  ;
                  } 
                  
              } 
           return  null ;
         } 

 


2、图片显示
Ajax请求发送成功之后的方法中的操作,
$("#img_identityA").attr("src","userregeste/file/showImages.do?name=identityA&"+new Date().toTimeString());
值得一提的是,img标签中的src属性,对于UI人员来说就是存放静态图片资源的,但是对于程序员来说,应该要知道img标签实际上会根据src属性去发送一次请求。同时,浏览器对于img的src属性的处理方式是如果src属性值不变,只会发送一次请求,所有加上new Date().toTimeString(),使每次的请求都不相同。
        @RequestMapping(value = "showImages")
        public String showImages(HttpServletRequest request,HttpServletResponse response) throws IOException { 
            
           OutputStream sout = null; 
        
           String name = request.getParameter("name"); // 图片名称
          
          
          byte[] pictrue = null; 
          // 从本地Map中去获取images图片 
           pictrue = images.get(name); 
         
           try { 
                if (pictrue != null) { 
                    response.setContentType("text/html"); 
                   sout = response.getOutputStream(); 
                   sout.write(pictrue); 
                 sout.flush(); 
                    sout.close(); 
                  sout = null; 
               } else { 
                    return null; 
                } 
           } catch (Exception e) { 
               e.printStackTrace(); 
           } finally { 
               if (sout != null) { 
                  sout.close(); 
                   sout = null; 
               } 
           } 
           return null; 
        }
       


*需要的jar包除了SpringMVC的所有jar包之外,还需要
commons-fileupload-1.3.1.jar
commons-io.jar
*设置enctype="multipart/form-data"后,表单数据是以二进制形式进行传输的,commons-fileupload-1.3.1.jar 即是帮我们解析二进制数据并且封装到parameter里面,不添加这个包,从HttpServletRequest获取不到参数,可以获取二进制流数据自行解析。
*以上的实现动态的将图片传送到后台,可以在后台对图片进行一系列处理,效率比较高


spring配置

  1. <!-- 图片获取 maxUploadSize:设置最大限制 字节为单位-->  
  2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  3.     <property name="maxUploadSize" value="1024000"></property>  
  4. </bean>  

如果是pom.xml的话

<!--图片上传jar包  --> 
 <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
 </dependency>
 <dependency>
    <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.4</version>
 </dependency>



     

0 0
原创粉丝点击