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

對不起,我編輯了這個問題 –

相關問題