如何通过Ajax提交在Spring MVC控制器中传递文件对象

4

我正在尝试通过jQuery Ajax提交传递文件对象。
JSP代码

<div id="import-file">
        <input type="file" id="file"/>
        <table>
        <tr><td><input type="radio" name="type" value="csv"></td><td>CSV File</td></tr>
        <tr><td><input type="radio" name="type" value="excel"></td><td>Excel spread sheet</td></tr>
        <tr><td><input type="radio" name="type" value="tab"></td><td>Tab delimited</td></tr>
        </table>
</div>

JavaScript代码

        var type = $($('input:radio:checked')[0]).val();
        var file = $("#file")[0].files[0];
        alert($("#file")[0].files[0].name);
        $.ajax({
            data :{
                "file" : file,
                "type" : type
            },
            type: "POST",
            url: "fileupload.htm",
            success: function(data){
                alert(data);
            },
            error:function(err){
                alert(err);
            }
        });

最后,这是我的Spring Controller 代码:

@RequestMapping(value="fileupload.htm",method=RequestMethod.POST )
    public @ResponseBody String uploadFile(@RequestParam String type, @RequestParam("file") MultipartFile file){
        logger.info("file type : "+type + "file is "+file.toString());
        return "SUCCESS";
    }

我在Firebug控制台中收到了NS_NOINTERFACE错误消息:Component does not have requested interface [nsIDOMBlob.slice]。


您必须传递 formData。 - adeneo
数据只是formData吗? - Ramesh Kotha
现在你正在传递文件对象,但那行不通,你需要传递文件本身,并且必须作为formData传递。 - adeneo
你能否纠正上面的代码并将其作为答案发布,这对我会很有帮助。 - Ramesh Kotha
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/42982/discussion-between-ramesh-k-and-adeneo - Ramesh Kotha
显示剩余2条评论
1个回答

9
我会尽力帮忙翻译。以下是您需要翻译的内容:

我是这样解决的:

JavaScript 代码

var formData = new FormData($('form')[0]);    
    console.log("form data "+formData);
    $.ajax({
        url: 'fileupload.htm',
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
            alert(data);
        },
        error: function(err){
            alert(err);
        }
    });

JSP 代码

<form action="fileupload.htm" method="post" enctype="multipart/form-data" name="fileinfo">
<input type="file" name="fileName" id="file"/>
</form>

Spring控制器:

@RequestMapping(value="fileupload.htm",method=RequestMethod.POST )
    public @ResponseBody String uploadFile(@RequestParam("fileName") MultipartFile file){
        try{
            logger.info("file is "+file.toString());

        }catch(Exception e){
            return "error occured "+e.getMessage();
        }
    }

希望这能对某些人有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接