问题
I have the following js code to send an Ajax request to a URL which maps a method in Spring MVC.
function update(id)
{
$.ajax({
datatype:"json",
type: "put",
url: "/wagafashion/ajax/TempAjax.htm",
data: "id=" + id+"&t="+new Date().getTime(),
success: function(response)
{
alert(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
and the following is the simple Spring form that has only a file browser and a button.
<form:form id="mainForm" name="mainForm" method="post" action="Temp.htm" enctype="multipart/form-data" commandName="tempBean">
<input type="file" id="myFile" name="myFile"/>
<input type="button" id="btnSubmit" name="btnSubmit" onclick="update(1);" value="Submit"/>
<!--The js function is called when this button is clicked supplying 1 as id.-->
</form:form>
The following method in Spring controller is invoked when that button is pressed.
@RequestMapping(method={RequestMethod.PUT}, value={"ajax/TempAjax"})
public @ResponseBody String update(HttpServletRequest request, HttpServletResponse response)
{
System.out.println(ServletFileUpload.isMultipartContent(request));
return "Message";
}
The method call ServletFileUpload.isMultipartContent(request)
however returns false
.
When I modify the method as follows,
@RequestMapping(method={RequestMethod.PUT}, value={"ajax/TempAjax"}, headers={"content-type=multipart/form-data"})
public @ResponseBody String update(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response)
{
System.out.println(ServletFileUpload.isMultipartContent(request));
return "Message";
}
the error section in the js code always alerts Error: [object Object]
. The same thing happens even if the POST
method is used, in this case.
How to pass multipart contents via Ajax (precisely using the PUT
method)?
回答1:
I can't really see how this is meant to post the multipart file to the server? The data just contains the id and a time.
Try something like:
function update(id)
{
$.ajax({
datatype:"json",
type: "put",
url: "/wagafashion/ajax/TempAjax.htm",
data: $('#mainForm').serialize(),
success: function(response)
{
alert(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
来源:https://stackoverflow.com/questions/13648599/how-to-upload-a-file-using-the-put-method-via-ajax-in-spring-mvc