javascript 如何使用spring mvc控制器通过ajax sumbit传递文件对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20528173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass file object through ajax sumbit with spring mvc controller
提问by Ramesh Kotha
I am trying to pass the file object through jquery ajax submit.
JSP code
我正在尝试通过 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>
Java script code
Java脚本代码
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);
}
});
finally here is my spring controller code:
最后这是我的弹簧控制器代码:
@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";
}
Am getting NS_NOINTERFACE: Component does not have requested interface [nsIDOMBlob.slice] error in my firebug console.
我收到 NS_NOINTERFACE: 组件在我的萤火虫控制台中没有请求的接口 [nsIDOMBlob.slice] 错误。
回答by Ramesh Kotha
I have solved it like this:
我是这样解决的:
JavaScript code
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 Code
JSP代码
<form action="fileupload.htm" method="post" enctype="multipart/form-data" name="fileinfo">
<input type="file" name="fileName" id="file"/>
</form>
Spring Controller:
弹簧控制器:
@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();
}
}
Hope it helps some body.
希望对身体有所帮助。