前端部分
使用ajaxfileupload 主要是为了异步上传文件,不需要开启新的页面进行上传!
由于segmentfault不能上传文件,该文件ajaxfileupload.js的代码在本篇文章的最底部:
由于ajaxfileupload这个文件已经很久没用更新了,所以增加了handleerror: function( s, xhr, status, e )来处理错误,
前端代码如下:第一个input中的accept属性是为了限制上传的文件属性,其他文件可以去掉该属性
引用两个js文件
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>
上传按钮:
<input type="file" id="upload" name="imagefile" accept="image/png,image/gif" />
<input type="button" value="上传" onclick="return ajaxfileupload();"/>
js代码:
//图片上传
function ajaxfileupload()
{
$.ajaxfileupload({
url:'/ai/app/uploadimage',//用于文件上传的服务器端请求地址
secureuri:false ,//一般设置为false
fileelementid:'upload',//文件上传控件的id属性 <input type="file" id="upload" name="upload" />
datatype: 'text',//返回值类型 一般设置为json
success: function (message) //服务器成功响应处理函数
{
layer.alert(message);
$("#tool_icon").val(message);
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
});
return false;
}
后端部分
该项目使用的spring框架,需要配置bean,来接受上传的文件
<!-- 上传文件拦截,设置最大上传文件大小 10m=10*1024*1024(b)=10485760 bytes -->
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<property name="maxuploadsize" value="10485760" />
</bean>
后端代码
@responsebody
@requestmapping(value="/uploadimage",method=requestmethod.post)
public string uploadimage(httpservletrequest request,@requestparam("imagefile") multipartfile file) throws ioexception{
string getoriginalfilename = null;
logger.debug("文件原名: " + getoriginalfilename);
logger.debug("文件名称: " + file.getname());
logger.debug("文件长度: " + file.getsize());
logger.debug("文件类型: " + file.getcontenttype());
if( file.isempty()){
logger.error("upload image--------------------------------->failed");
return "please select a image";
}
/**文件在服务器中的实际路径*/
string realpath = request.getsession().getservletcontext().getrealpath("/upload");
logger.debug("realpath---------------------------------------->"+realpath);
logger.debug("getoriginalfilename----------------------------->"+file.getoriginalfilename());
/**写入地址中*/
fileutils.copyinputstreamtofile(file.getinputstream(), new file(realpath,file.getoriginalfilename()));
/**使用原生方法*/
/* byte[] bytes = file.getbytes();
bufferedoutputstream stream = new bufferedoutputstream(new fileoutputstream(new file("/ai/images/icons/toollogo/demo.png")));
stream.write(bytes);
stream.close();*/
/**返回文件在服务器中的地址,用于存储入库*/
string resulturl = "/ai/upload/"+file.getoriginalfilename();
logger.debug("upload image file result----------------------->"+resulturl);
return resulturl;
}
ajaxfileupload.js 源代码
// javascript document
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;
}
}
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 = jquery('<form action="" method="post" name="' + formid + '" id="' + formid + '" enctype="multipart/form-data"></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 = s.fileelementid;
var form = jquery.createuploadform(id, s.fileelementid);
var io = jquery.createuploadiframe(id, s.secureuri);
var frameid = 'juploadframe' + id;
var formid = 'juploadform' + id;
if( s.global && ! jquery.active++ )
{
// watch for a new set of requests
jquery.event.trigger( "ajaxstart" );
}
var requestdone = false;
// create the request object
var xml = {};
if( s.global )
{
jquery.event.trigger("ajaxsend", [xml, s]);
}
var uploadcallback = function(istimeout)
{
// wait for a response to come back
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( s.success )
{
// ifa local callback was specified, fire it and pass it the data
s.success( data, status );
};
if( s.global )
{
// fire the global callback
jquery.event.trigger( "ajaxsuccess", [xml, s] );
};
} else
{
jquery.handleerror(s, xml, status);
}
} catch(e)
{
status = "error";
jquery.handleerror(s, xml, status, e);
};
if( s.global )
{
// the request was completed
jquery.event.trigger( "ajaxcomplete", [xml, s] );
};
// handle the global ajax counter
if(s.global && ! --jquery.active)
{
jquery.event.trigger("ajaxstop");
};
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(){
if( !requestdone )
{
// check to see ifthe request is still happening
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)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
jquery(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;
// ifthe type is "script", eval it in global context
if( type == "script" )
{
jquery.globaleval( data );
}
// get the javascript object, ifjson is used.
if( type == "json" )
{
eval( "data = " + data );
}
// evaluate scripts within html
if( type == "html" )
{
jquery("<div>").html(data).evalscripts();
}
return data;
},
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] );
}
}
});