0

我有一个图像文件,我需要从我的jsp页面发送,并在我的控制器页面使用JavaScript ajax调用读取。 在jsp页面的警告似乎是shoeing文件对象被正确读取,但是没有收到控制器和ajax发送者错误响应而不是成功。从jsp发送文件到弹簧控制器使用ajax

以下是代码片段即时通讯使用

JSP文件

<table> 
<tr> 
    <td>Profile Picture</td> 
    <td><input type="file" id="profilePic"></td> 
</tr> 
<tr> 
    <td colspan="2"><button id="updatePic" onclick="pic();">submit pic</button></td> 
</tr> 
</table> 

的JavaScript上的Spring MVC我们

function pic() { 
     var formData = new FormData(); 
     formData.append("profilePic", $('#profilePic').get(0).files[0]); 
      $.ajax({ 
      type:"POST", 
      url:"/sdnext/updateprofile.html", 
      processData: false, 
      contentType: false, 
      data:{profilePic:formData}, 
      success:function(data){ 
       alert("Profile Picture has been updated successfully"); 
      }, 
      error:function(data){ 
       alert("Profile Picture has not been updated successfully"); 
      } 
     }); 
} 

控制器

@RequestMapping(value="/updateprofile",method=RequestMethod.POST) 
     public @ResponseBody String updateProfile(@RequestParam("profilePic") InputStream profilePic){ 

    try { 
       int i=0; 
       ArrayList<Byte> listOfBytes=new ArrayList<Byte>(); 
       InputStream input=profilePic.getInputStream(); 
       do{ 
        i=input.read(); 
        if(i!=-1) 
        { 
         listOfBytes.add((byte) i); 
        } 
       }while(i!=-1); 
       System.out.println(listOfBytes.size()); 
       byte []picBytes=new byte[listOfBytes.size()]; 
       for (int j = 0; j < listOfBytes.size(); j++) { 
        picBytes[j]=listOfBytes.get(j); 
       } 

     } catch (IOException e) { 

       e.printStackTrace(); 
     } 

    } 

任何样品FileIO专注操作阿贾克斯将是非常有益的。任何帮助将不胜感激 。

感谢

回答

0

检查this答案。它有详细的如何做到这一点。

+1

正如我在问题陈述中所述,我不想要包含表单提交的解决方案,例如。我希望有一个包含ajax组件的解决方案,以便页面不必重新加载。 – Altanai

+0

对不起,我编辑了这个问题 –