[英]How can I submit a form and upload a file using ajax to a spring controller?
I have a form which contains four fields, the file, the name, the type (just a string) and the taskInstanceId. 我有一个包含四个字段的表单,文件,名称,类型(仅一个字符串)和taskInstanceId。
<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>
If I submit this form it will connect to my FileUploadController and the file will upload. 如果我提交此表单,它将连接到我的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
Now I would like to submit this form using jquery/json instead so that I can return a string indicating a successful upload and then display a dialog on the page indicating this. 现在,我想改为使用jquery / json提交此表单,以便我可以返回一个指示成功上传的字符串,然后在页面上显示一个对话框以表明这一点。 (I don't want to return a new ModelAndView). (我不想返回一个新的ModelAndView)。
So using the same html form I create a new Controller function... 因此,使用相同的html表单,我创建了一个新的Controller函数...
@RequestMapping(value = "/formTask2.json", method = RequestMethod.POST)
public String handleFormTaskUpload2(UploadTaskDocument myNewUpload)).../rest of the code
Now I would like to submit the form above using jQuery. 现在,我想使用jQuery提交上面的表单。 My attempt is here. 我的尝试在这里。
This function is called everytime the file is changed. 每次更改文件时都会调用此函数。
function prepareUpload(event)
{
files = event.target.files;
}
And this one is called when the form is submitted. 提交表单时将调用此名称。
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
}
});
}
The Json data looks like this before it's posted... Json数据在发布之前看起来像这样...
But once it reaches the server everything is null... 但是一旦到达服务器,一切都将为空...
Ok this might seem a bit different than your solution but I would go forth by doing the following. 好的,这似乎与您的解决方案有所不同,但是我将通过执行以下操作来解决。
As I understand you want to upload the data using ajax to your controller and avoid a post back, and then return a string and nothing but a string. 据我了解,您想使用ajax将数据上传到控制器,并避免回发,然后返回一个字符串,仅返回一个字符串。 I would do as follows. 我会做如下。
You have your form: 您的表格如下:
<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>
Your JQuery: 您的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
}
});
}
In your controller: 在您的控制器中:
As you are working with MVC, please use a Model as it is the correct fashion to catch a parameter. 在使用MVC时,请使用模型,因为这是捕获参数的正确方式。
public String handleFormTaskUpload2(UploadedFile mynewUpload )
{
//rest of code here
}
Your Model will then look something to this. 然后,您的模型将对此具有某种外观。
public class UploadedFile
{
public string documentName{get;set}
public string documentType{get;set}
public string taskInstanceId{get;set}
prop List<byte[]> files {get;set}
}
Hope this helps, please let me know if you still don't understand 希望对您有所帮助,如果您仍然不明白,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.