经常碰到文件上传的问题,这里使用ajax提供的ajaxFileUpload来解决
HTML页面:
JS:
*这里需要导入ajaxfileupload.js. 并且需要对文件的uploadHttpData进行修改,修改后
原因是在使用json对象时,会自动在返回数据里加入<pre></pre>,导致解析失败。
Java使用SpringMVC
这里需要使用common-fileupload这个jar包,对应的maven配置如下:
HTML页面:
<form class="form-inline" action="" id="fileUpload" method="POST" enctype="multipart/form-data">
<div class="col-sm-12" align="right">
<div class="float-box">
<input id="excelFile" name="excelFile" type="file"/>
</div>
<div class="float-box">
<button type="button" class="btn btn-danger" ng- click="uploadExcel(altPart.id)">Add</button>
</div>
</div>
</form>
JS:
$.ajaxFileUpload({
url : 'altparts/uploadExcel',
secureuri : false,
fileElementId : 'excelFile',
dataType : 'json',
data : {},
success : function(data, status) {
alert('upload successfully');
$location.path('altparts/');
},
error : function(data, status, e) {
alert('upload exception');
}
});
*这里需要导入ajaxfileupload.js. 并且需要对文件的uploadHttpData进行修改,修改后
uploadHttpData: function( r, type ) {
var data = !type;
var dataparsed = r.responseText.split("{");
dataparsed = dataparsed[1].split("}");
data = type == "xml" || "{ " + dataparsed[0] + " }";
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
},
原因是在使用json对象时,会自动在返回数据里加入<pre></pre>,导致解析失败。
Java使用SpringMVC
@RequestMapping(value = "/uploadExcel", method = RequestMethod.POST, consumes = "multipart/form-data", produces = "application/json")
public @ResponseBody List<Part> uploadExcel(@RequestParam MultipartFile[] excelFile) {
String fileName = excelFile[0].getOriginalFilename();
if (fileName.lastIndexOf(".xls")==4) {
return analyzeXLS(excelFile[0]);
} else {
return analyzeXLSX(excelFile[0]);
}
}
这里需要使用common-fileupload这个jar包,对应的maven配置如下:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>