1.依附于用了jquery所以需要先导包,然后添加这一个js文件代码如下:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
/* if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}*/
if(window.ActiveXObject) { //修改以后的代码
if(jQuery.browser.version=="9.0" || jQuery.browser.version=="10.0"){
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0"){
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
} //修改以后的代码
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
addOtherRequestsToForm: function(form,data)
{
// add extra parameter
var originalElement = $('<input type="hidden" name="" value="">');
for (var key in data) {
name = key;
value = data[key];
var cloneElement = originalElement.clone();
cloneElement.attr({'name':name,'value':value});
$(cloneElement).appendTo(form);
}
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);
if ( s.data ) form = jQuery.addOtherRequestsToForm(form,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
{
$(io).remove();
$(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 io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
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" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
var am = rx.exec(data);
//this is the desired data extracted
var data = (am) ? am[1] : ""; //the only submatch or empty
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
2.1.前台的html代码片段如下:
<div class="pM-m-formCell" style = "margin-left: 15px">
<input type="file" name="impFile" id="user_file" style="width:200px">
</div>
<div class="pM-m-formCell" style = "margin-left: 15px;margin-right: 15px">
批量导入注意事项:表头顺序等信息请参照模版,导入完成需下载EXCEL文件查看导入反馈信息!
</div>
2.2.页面上的js代码如下:
//批量导入方法
function do_Excel(){
$.messager.confirm("导入确认","导入时间可能会很长,请耐心等待,请勿做其他操作!",function (res) {
if (res) {
var path = $("#user_file").val();//文件全称
if(path=="" || path==null){
$.messager.alert("系统提示","请上传文件后再导入!","info");
return ;
}
var suffix = path.substring(path.lastIndexOf("."));//文件后缀名
var allowedSuffix = ".xlsx、.xls";
if(allowedSuffix.indexOf(suffix) < 0){//校验上传文件的类型
$.messager.alert("系统提示","请上传后缀为【"+ allowedSuffix +"】的文件","info");
return ;
}
$.ajaxFileUpload({
url: '。。。',//用于文件上传的服务器端请求地址
secureuri: false,//一般设置为false
fileElementId: 'user_file', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'JSON',//返回值类型 一般设置为json,大写
data: {},
type: 'post',
success: function(result,status){//服务器成功响应处理函数
var data = $.parseJSON(result);//json对象的反序列化
if(data.stat == "1") {
$('#id').window('close');
$.messager.alert("系统提示",data.message,"info");
//下载返回模板
var fileName = data.data;
var downloadUrl = "。。。";
jQuery('<form action="'+downloadUrl+'" method="'+('post')+'">' + // action请求路径及推送方法
'<input type="text" name="fileName" value="'+fileName+'"/>' + // 文件名称
'</form>')
.appendTo('body').submit().remove();
}else{
$.messager.alert("系统提示",data.message,"info");
}
// 隐藏遮罩
$.messager.progress('close');
}
});
}
});
}
3.后台接收文件的Java代码,如下:
public JSON impTagUsers(@RequestParam(value = "impFile", required = false) MultipartFile file, HttpServletRequest request) {
if (Empty.isNotEmpty(file)) {
//获取文件的后缀名
String originalFileName = file.getOriginalFilename();
String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
InputStream is = null; // 获取输入文件流
try {
is = file.getInputStream();
//接收数据
Workbook workbook = null;
if (suffix.equals(".xls")) {//2003版之前表格
workbook = new HSSFWorkbook(is);
} else {//XSSFWorkbook用来解析2007之后的版本(xlsx)
workbook = new XSSFWorkbook(is);
}
Sheet sheet = workbook.getSheetAt(0);//批量导入的excel文件的数据
String fileName = "处理自己的逻辑";
return ResultData.success("导入成功",fileName).toJson();
}catch (Exception e) {
e.printStackTrace();
return ResultData.failureToJson("导入失败");
}
} else {
return ResultData.failureToJson("导入失败");
}
}
4.附带文件下载的java后台代码,前台不能用ajax发送请求,可以模拟表单提交或者用超链接
public void downloadTemp(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "fileName",required = false) String fileName) {
//获取项目的根目录下的指定目录
String path = request.getSession().getServletContext().getRealPath("/") + File.separator + "Excel" + File.separator;
if (Empty.isEmpty(fileName)) {//为空时下载模板,或者前台传入的文件名参数为空时也会下载模板
path += "模板名称.xls";
} else {//不为空时下载反馈文件
path += fileName;
}
File file = new File(path);
FileInputStream in = null;
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(response.getOutputStream());
response.reset();
//解决浏览器文件名中文乱码兼容问题
String repFileName = file.getName();
String agent = request.getHeader("User-Agent");
//针对IE或者以IE为内核的浏览器:
if (agent.contains("MSIE") || agent.contains("Trident")) {
repFileName = URLEncoder.encode(repFileName, "UTF-8");
} else {
repFileName = new String(repFileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", repFileName));
response.setContentType("application/ms-excel;charset=utf-8");
response.setCharacterEncoding("UTF-8");
in = new FileInputStream(file);
int count = 0;
byte[] buffer = new byte[1024];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//删除导入时存放的零时文件,fileName零时文件名
if (Empty.isNotEmpty(fileName)) {
if (file.exists()) {
file.delete();
}
}
}