总结一下 springMvc使用ajax文件上传
首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回excel文件内容给前端并显示。
难点主要在于controller如何或得前端传递过来的文件,或者文件流
前端引用 :ajaxfileupload.js
ajaxfileupload.js 代码:
jQuery.extend({
//扩展函数
handleError: function( s, xhr, status, e ){
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
} // Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}, createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"'; }
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"'; }
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0);
}, createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form); //set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
}, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime();
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {};
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status ); // Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
} // The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" ); // Process result
if ( s.complete )
s.complete(xml, status); jQuery(io).unbind(); setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, 100); xml = null; }
};
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{ var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
}, uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// 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(); if ( type == "json" ){
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
}
return data;
} });
html代码:
<div id="fileUpLoad" class="manage">
<div style="display: none;">
<input type="file" id="btnFile" name="btnFile" />
</div>
<input type="text" id="txtFoo" readonly="readonly" style="width:300px" />
<button onclick="btnFile.click()" style="height: 25px;">选择文件</button>
</div>
javaScript代码:
<script>
function confirm(){ var fileName = $("#btnFile").val();//文件名
fileName = fileName.split("\\");
fileName = fileName[fileName.length-1];
jQuery.ajaxSettings.traditional = true;
$.ajaxFileUpload({
url : '${pageContext.request.contextPath }/plan/fileUpLoads.do',
secureuri : false,//安全协议
fileElementId:'btnFile',//id
type : 'POST',
dataType : 'text',
error : function(data) { },
success : function(data) { var start = data.indexOf("[");
var end = data.indexOf("]");
var jsonStr = data.substring(start,end+1);
var foreach = "{'row':"+jsonStr+"}";
var json = eval("("+foreach+")"); ty="";
jQuery.each(json.row, function(i,item){ var _len = item.operation;
ty +="<tr class='lay0 taskTitle' id="+_len+" align='center'>"
+"<td style='text-align:center'>"+_len+"</td>"
+"<input type='hidden' name='num_"+_len+"' value="+_len+" /><input type='hidden' name='planid_"+_len+"' value='' />"
+"<td><input type='text' size=25 name='title_"+_len+"' value='"+item.eventnode+"' id='desc"+_len+"' /></td>"
+"<td><input type='text' size=30 name='method_"+_len+"' id='method"+_len+"' value='"+item.workplan+"'/></td>"
+"<td><input type='text' size=25 name='steps_"+_len+"' id='steps"+_len+"' value='"+item.chengguomiaoshu+"'/></td>"
+"<td><input type='text' size=12 name='time_"+_len+"' value='"+item.completetime+"' id='time"+_len+"' onClick='WdatePicker()'/></td>"
+"<td> <input type='text' size=14 name='leader_name"+_len+"' wrap='yes' readonly value='"+item.person+"' ><a href='javascript:;' class='orgAdd'>添加</a> <a href='javascript:;' class='orgdel'>清空</a></td>"
+"<td><a href='javascript:void(0);' onclick='addchild("+_len+")'>添加节点</a><br/><a href='javascript:void(0);' onclick='deltr("+_len+")'>删除节点</a></td>"
+"</tr>"; });
$("#taskContent").append(ty);
}
}); $('.myModal1,.mask').hide();
} </script>
这里ajax 的 dataType : 'text',如果这里是json类型就会接不到ajax返回的数据
success : function(data) {}这里的data 是 ajax成功后数据,因为dataType:'text'的缘故,这里的data并不是json数据,也不可直接使用,上述success方法里的
var start = data.indexOf("[");
var end = data.indexOf("]");
var jsonStr = data.substring(start,end+1);
var foreach = "{'row':"+jsonStr+"}";
var json = eval("("+foreach+")");
就是将data转化为json格式 controller代码:
//btnFile对应页面的name属性
@RequestMapping("/fileUpLoads")
public @ResponseBody List<OnlineAddplanWithBLOBs> fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){
List<OnlineAddplanWithBLOBs> list = new ArrayList<OnlineAddplanWithBLOBs>();
InputStream is;
try {
//文件类型:btnFile[0].getContentType()
//文件名称:btnFile[0].getName()
is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件 POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb=new HSSFWorkbook(fs);
HSSFSheet hssfSheet=wb.getSheetAt(0); // 获取第一个Sheet页
if(hssfSheet!=null){
for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
HSSFRow hssfRow=hssfSheet.getRow(rowNum);
if(hssfRow==null){
continue;
}else{
OnlineAddplanWithBLOBs bean = new OnlineAddplanWithBLOBs();
bean.setOperation(ExcelUtil.formatCell(hssfRow.getCell(0)));
bean.setEventnode(ExcelUtil.formatCell(hssfRow.getCell(1)));
bean.setWorkplan(ExcelUtil.formatCell(hssfRow.getCell(2)));
bean.setChengguomiaoshu(ExcelUtil.formatCell(hssfRow.getCell(3)));
bean.setCompletetime(ExcelUtil.formatCell(hssfRow.getCell(4)));
bean.setPerson(ExcelUtil.formatCell(hssfRow.getCell(5)));
System.out.println("序号是 "+bean.getOperation());
System.out.println("事项节点是 "+bean.getEventnode());
System.out.println("工作思路是 "+bean.getWorkplan());
System.out.println("成果描述是 "+bean.getChengguomiaoshu());
if(!"".equals(bean.getEventnode())){
System.out.println("=========== 有添加数据 ");
list.add(bean);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
这里是controller的代码 核心代码就是读取excel文件流
InputStream is = btnFile[0].getInputStream();//获取excel文件输入流
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb=new HSSFWorkbook(fs);
HSSFSheet hssfSheet=wb.getSheetAt(0);
HSSFRow hssfRow=hssfSheet.getRow(rowNum);
ExcelUtil.formatCell()这个方法是将获取单元格的内容转换成字符串
public static String formatCell(HSSFCell hssfCell){
if(hssfCell==null){
return "";
}else{
if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
return String.valueOf(hssfCell.getBooleanCellValue());
}else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
return String.valueOf(hssfCell.getNumericCellValue());
}else{
return String.valueOf(hssfCell.getStringCellValue());
}
}
}
struts2文件上传 html代码:
<form id="uploadForm" action="user!upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>下载模版:</td>
<td><a href="javascript:void(0)" class="easyui-linkbutton" onclick="downloadTemplate()">导入模版</a></td>
</tr>
<tr>
<td>上传文件:</td>
<td><input type="file" name="userUploadFile"></td>
</tr>
</table>
</form>
action代码
private File userUploadFile; public File getUserUploadFile() {
return userUploadFile;
}
public void setUserUploadFile(File userUploadFile) {
this.userUploadFile = userUploadFile;
} public String upload()throws Exception{
POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(userUploadFile));
HSSFWorkbook wb=new HSSFWorkbook(fs);
HSSFSheet hssfSheet=wb.getSheetAt(0); // 获取第一个Sheet页
if(hssfSheet!=null){
for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
HSSFRow hssfRow=hssfSheet.getRow(rowNum);
if(hssfRow==null){
continue;
}
User user=new User();
user.setName(ExcelUtil.formatCell(hssfRow.getCell(0)));
user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1)));
user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2)));
user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3))); }
} return null;
}
struts.xml 直接配置一下映射就可以了