如何在 Spring MVC 中通过 Ajax 使用 PUT 方法上传文件?

IT小君   2022-09-15T08:31:16

我有以下 js 代码将 Ajax 请求发送到映射 Spring MVC 中的方法的 URL。

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方法)?

点击广告,支持我们为你提供更好的服务
评论(1)
IT小君

我真的不明白这是如何将多部分文件发布到服务器的?数据只包含 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);
        }
    });
}
2022-09-15T08:31:16   回复