第一次出差到深圳,帮朋友给一个项目收尾,客户临时要求上传文件的时候顺便上传封面,所以就想到用异步上传的方式,然后在前端预览上传的图片,于是就用到了“ajaxFileUpload”这一款基于“jquery”的上传插件,刚拿到手的时候去网上查了一下他的用法,然后理所当然的在返回值的时候用json传递数据,但是这个时候,IE浏览器开始不兼容了,报了一个什么语法错误这样一个错,后来才发现,IE浏览器好像不支持回传json格式的数据,只能传回json字符串然后转成json对象,于是在这里记录一下代码,以便重复利用。
js部分
function deletimg(){
$("#img").css("display","none");
$("#imgText").val("");
$("#img")[0].src="";
$("#imgfile").css("display","block");
$("#delimg").css("display","none");
}
function uploadImg(){
var f = $("#imgfile").val();
var extname = f.substring(f.lastIndexOf(".")+1,f.length);
extname = extname.toLowerCase();//处理了大小写
if(extname!= "jpeg"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){
alert("格式不正确,支持的图片格式为:JPEG、GIF、PNG!");
return false;
}
var file = document.getElementById("imgfile").files;
var size = file[0].size;
if(size>2097152){
alert("所选择的图片太大,图片大小最多支持2M!");
return false;
}
ajaxFileUploadPic();
}
function ajaxFileUploadPic() {
$.ajaxFileUpload({
url : 'fileupload/uploadImg', //用于文件上传的服务器端请求地址
secureuri : false, //一般设置为false
fileElementId : "imgfile", //文件上传空间的id属性 <input type="file" id="file" name="file" />
type : 'post',
dataType : 'text', //返回值类型 一般设置为json
success : function(data, status) //服务器成功响应处理函数
{
alert(data);
var obj = eval('(' + data + ')');
if(obj.result=="success"){
$("#img").css("display","block");
$("#imgText").val(obj.url);
$("#img")[0].src=obj.url;
$("#imgfile").css("display","none");
$("#delimg").css("display","block");
}else{
alert("图片上传失败,请重试。错误原因:"+obj.msg);
}
},
error : function(data, status, e)//服务器响应失败处理函数
{
alert("图片上传失败,请重试。");
//alert(data);
//alert(e);
}
});
return false;
}
jsp部分
<input type="file" name="imgfile" id="imgfile" placeholder="请选择封面文件" οnchange="uploadImg()">
<img id="img" style="height:100px;width:auto;display:none;">
<input type="hidden" id="imgfileText">
<input type="button" id="delimg" οnclick="deletimg()" value="删除图片" style="display:none">
@RequestMapping(value = "/uploadImg")
public Map<String, Object> uploadImg2(HttpServletRequest request,
HttpServletResponse response, MultipartHttpServletRequest req) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile uploadFile = null;
uploadFile = multipartRequest.getFile("imgfile");// 获取上传文件名
response.setContentType("text/html;charset=utf-8");
try {
//文件保存目录路径
String savePath = request.getSession().getServletContext().getRealPath("/") + "uploadFiles/KJIMG/";
//文件保存目录URL
String saveUrl = request.getContextPath() + "/uploadFiles/KJIMG/";
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
uploadDir.mkdirs();
}
//检查目录写权限
if(!uploadDir.canWrite()){
response.getWriter().write("{\"result\":\"error\",\"msg\":\"上传目录没有写权限。\"}");
return null;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
//创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String fileName = uploadFile.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath + newFileName));
FileCopyUtils.copy(uploadFile.getInputStream(), outputStream);
response.getWriter().write("{\"result\":\"success\",\"url\":\""+saveUrl + newFileName+"\"}");
} catch (Exception e) {
e.printStackTrace();
try {
response.getWriter().write("{\"result\":\"error\",\"msg\":\""+e.getMessage()+"\"}");
} catch (IOException e1) {
e1.printStackTrace();
}
}
return null;
}
ajaxFileUpload.js部分
jQuery.extend({
handleError: function (s, xhr, status, e) {
if (s.error) {
s.error.call(s.context || s, xhr, status, e);
}
if (s.global) {
(s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
}
},
httpData: function (xhr, type, s) {
var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.tagName == "parsererror")
throw "parsererror";
if (s && s.dataFilter)
data = s.dataFilter(data, type);
if (typeof data === "string") {
if (type == "script")
jQuery.globalEval(data);
if (type == "json")
data = window["eval"]("(" + data + ")");
}
return data;
},
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 = $('<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;
},
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;
// 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" ){
// 因为json数据会被<pre>标签包着,所以有问题,现在添加以下代码,
// update by hzy
var reg = /<pre.+?>(.+)<\/pre>/g;
var result = data.match(reg);
result = RegExp.$1;
// update end
data = $.parseJSON(result);
// 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;
}
})
Controller部分