2012-11-30 37 views
0

我有以下js代码发送一个Ajax请求到一个映射在Spring MVC中的方法的URL。如何在Spring MVC中通过Ajax使用PUT方法上传文件?

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); 
     } 
    }); 
} 

以下是只有文件浏览器和按钮的简单的Spring窗体。

<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> 

当按下按钮时,会调用Spring控制器中的以下方法。

@RequestMapping(method={RequestMethod.PUT}, value={"ajax/TempAjax"}) 
public @ResponseBody String update(HttpServletRequest request, HttpServletResponse response) 
{ 
    System.out.println(ServletFileUpload.isMultipartContent(request)); 
    return "Message"; 
} 

方法调用但是ServletFileUpload.isMultipartContent(request)返回false


当我修改方法如下,

@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"; 
} 

在JS代码中的错误部分总是警报Error: [object Object]。在这种情况下,即使使用POST方法也会发生同样的情况。

如何通过Ajax传递多部分内容(正确使用PUT方法)?

回答

0

我真的不明白这是如何将多部分文件发布到服务器?数据只包含id和时间。

试着这么做:

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); 
     } 
    }); 
} 
+0

错误节只说警告框, “*错误:[对象的对象] *” 即使有'数据:$( '#的MainForm')序列化() ,',没有运气。 – Tiny

+0

您是否在春季环境中定义了多重解析器?如此处所述http://stackoverflow.com/a/13405415/302387 –

+0

是的,我已经在我的'applicationContext.xml'文件中定义了'MultipartResolver',它工作正常(没有Ajax),但JavaScript总是说“*错误: [对象对象] *“,以防Ajax。 – Tiny