我有一個表單,其中包含四個字段,文件,名稱,類型(只是一個字符串)和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數據看起來像這樣...
但是,一旦它到達服務器一切都是空...
是的,看起來還好,除了在'jQuery.ajax'通話的研製成功情況下,你'submitForm'。不知道「submitForm」的作用是什麼,但它不能再提交表單了,因爲你已經用ajax請求發送了數據。在成功案例中,如果處理了表單數據並且您已從服務器獲得成功響應,則調用應執行的操作。 – Bernhard
忽略這一點,我只是沒有編碼的階段呢。 我現在遇到的問題是,當我嘗試提交ajax時出現404錯誤,我不知道爲什麼? – OneTwo