2015-06-24 51 views
0

我有一個表單,其中包含四個字段,文件,名稱,類型(只是一個字符串)和taskInstanceId。如何使用ajax提交表單並上傳文件到彈簧控制器?

<form> 
    <table id="documentDetailsTable"> 
     <tr> 
      <td>Document Type: </td> 
      <td><select id="documentType" name="type"> </select></td> 
     </tr> 
     <tr> 
      <td> 
       Document Name: 
      </td> 
      <td> 
       <input type="text" id="documentName" name="name"/> 
      </td> 
     </tr> 
     <tr id="newFile"> 
      <td> 
       Choose a file: 
      </td> 
      <td> 
       <input type="file" name="file" /> 
      </td> 
    </table> 
    <input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId"> 

    <input id="uploadButton" value="Upload" type="submit"/> 
    <input class="closeButton" id="closeNew" value="Close" type="button"/> 
</form> 

如果我提交這個表單,它將連接到我的FileUploadController並且文件將被上傳。

@RequestMapping(value = "/formTask.do", method = RequestMethod.POST) 
public ModelAndView handleFormTaskUpload(@RequestParam("name") String name, 
     @RequestParam("type") String type, 
     @RequestParam("file") MultipartFile file, 
     @RequestParam("taskInstanceId") int taskInstanceId)...//rest of the code 

現在我想使用jQuery/JSON而不是提交此表,這樣我可以表明這個頁面上的返回一個字符串,指示上傳成功,然後顯示一個對話框。 (我不想返回一個新的ModelAndView)。

因此,使用相同的HTML表單創建一個新的控制器功能...

@RequestMapping(value = "/formTask2.json", method = RequestMethod.POST) 
public String handleFormTaskUpload2(UploadTaskDocument myNewUpload)).../rest of the code 

現在我想提交上述使用jQuery形式。我的嘗試在這裏。

每次更改文件時都會調用此函數。

function prepareUpload(event) 
{ 
    files = event.target.files; 
} 

而且這個在表單提交時被調用。

function uploadFiles(event) 
{ 
event.stopPropagation(); // Stop stuff happening 
event.preventDefault(); // Totally stop stuff happening 

var data; 
data = { 
    documentName: $("#documentName").val(), 
    documentType: $("#documentType").val(), 
    taskInstanceId: selectedTaskInstanceId, 
    uploadedfiles: files 
}; 
var json = JSON.stringify(data); 
$.ajax({ 
    url: '/SafeSiteLive/formTask2.json', 
    type: 'POST', 
    data: json, 
    cache: false, 
    dataType: 'json', 
    processData: false, // Don't process the files 
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request 
    success: function (data, textStatus, jqXHR) 
    { 
     if (typeof data.error === 'undefined') 
     { 
      // Success so call function to process the form 
      //submitForm(event, data); 
     } 
     else 
     { 
      // Handle errors here 
      console.log('ERRORS: ' + data.error); 
     } 
    }, 
    error: function (jqXHR, textStatus, errorThrown) 
    { 
     // Handle errors here 
     console.log('ERRORS: ' + textStatus); 
     // STOP LOADING SPINNER 
    } 
}); 
} 

它發佈之前JSON數據看起來像這樣...

enter image description here

但是,一旦它到達服務器一切都是空...

enter image description here

+1

是的,看起來還好,除了在'jQuery.ajax'通話的研製成功情況下,你'submitForm'。不知道「submitForm」的作用是什麼,但它不能再提交表單了,因爲你已經用ajax請求發送了數據。在成功案例中,如果處理了表單數據並且您已從服務器獲得成功響應,則調用應執行的操作。 – Bernhard

+0

忽略這一點,我只是沒有編碼的階段呢。 我現在遇到的問題是,當我嘗試提交ajax時出現404錯誤,我不知道爲什麼? – OneTwo

回答

1

好這可能看起來有點不同於你的解決方案,但我會繼續做下面的事情。

據我所知,您希望使用ajax將數據上傳到您的控制器,並避免發回帖子,然後返回一個字符串而不是字符串。我會做如下。

你有你的形式:

<form> //Remove the method type as well as where the post should happen to ensure that you do not have to prevent default behavior 
    <table id="documentDetailsTable"> 
     <tr> 
      <td>Document Type: </td> 
      <td><select id="documentType" name="type"> </select></td> 
     </tr> 
     <tr> 
      <td> 
       Document Name: 
      </td> 
      <td> 
       <input type="text" id="documentName" name="name"/> 
      </td> 
     </tr> 
     <tr id="newFile"> 
      <td> 
       Choose a file: 
      </td> 
      <td> 
       <input type="file" name="file" /> 
      </td> 
    </table> 
    <input type="text" style="display: none;" name="taskInstanceId" id="taskInstanceId"> 

    <input id="uploadButton" value="Upload" onclick('uploadFiles()')/> //Add //the event to your submit button and remove the submit from itself 
    <input class="closeButton" id="closeNew" value="Close" type="button"/> 
</form> 

你的JQuery:

//Stays the same I would suggest using a object type and then stringify it as follows 
function uploadFiles(event) 
{ 
event.stopPropagation(); // Stop stuff happening 
event.preventDefault(); // Totally stop stuff happening 

// START A LOADING SPINNER HERE 

// Create a formdata object and add the files 
//var data = new FormData(); 
//.each(files, function (key, value) 
//{ 
// data.append(key, value); 
//}); 
//data.append('documentName', $("#documentName").val()); 
//data.append('documentType', $("#documentType").val()); 
//data.append('taskInstanceId', $("#taskInstanceId").val()); 

// Create a objectobject and add the files 
var data; 
data = { 
    documentName:$("#documentName").val(), 
    documentType:$("#documentType").val(), 
    taskInstanceId:$("#taskInstanceId").val(), 
    uploadedfiles: files 
} 
var json = JSON.stringify(data); 
$.ajax({ 
    url: '/SafeSiteLive/formTask2.do', 
    type: 'POST', 
    data: json, 
    cache: false, 
    dataType: 'json', 
    processData: false, // Don't process the files 
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request 
    success: function (data, textStatus, jqXHR) 
    { 
     if (typeof data.error === 'undefined') 
     { 
      // Success so call function to process the form 
      submitForm(event, data); 
     } 
     else 
     { 
      // Handle errors here 
      console.log('ERRORS: ' + data.error); 
     } 
    }, 
    error: function (jqXHR, textStatus, errorThrown) 
    { 
     // Handle errors here 
     console.log('ERRORS: ' + textStatus); 
     // STOP LOADING SPINNER 
    } 
}); 
} 

在你的控制器:

當你與MVC工作,請使用一個模型,因爲它是正確的追趕參數的時尚。

public String handleFormTaskUpload2(UploadedFile mynewUpload) 
{ 
//rest of code here 
} 

您的模型將看起來像這樣。

public class UploadedFile 
{ 
    public string documentName{get;set} 
    public string documentType{get;set} 
    public string taskInstanceId{get;set} 
    prop List<byte[]> files {get;set} 
} 

希望這會有所幫助,請讓我知道,如果你還是不明白

+0

感謝你這看起來像一個更乾淨的方式做到這一點,它擺脫了我的404錯誤。但由於某些原因,到達服務器的數據爲空。我用我正在使用的新代碼更新了我的主帖子... – OneTwo

相關問題