使用ajaxfileupload的一点心得

来源:互联网 发布:网络dm什么意思 编辑:程序博客网 时间:2024/06/06 02:20

ajaxfileupload大概是因为很久不更新,所有有不少的问题

1、handlerError not find

这个东西从jQuery1.4之后就已经没有了,所以需要手动添加到ajaxfileupload.js中

(插在js文件内部)

<span style="color:#ff0000;">    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] );          }      } ,</span>    createUploadIframe: function(id, uri)    {    //create frame    var frameId = 'jUploadFrame' + id;            


2、携带参数传递文件

因为ajaxfileupload是创建了form传递的,然而作者并没有把data的内容加入到form中,所以需要手动添加

红色部分为添加的内容,共3处

<span style="color:#ff0000;">createUploadForm: function(id, fileElementId,data)</span>    {    //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);//add data to form    <span style="color:#ff0000;">if(data){    for(var i in data){    //alert(i+":"+data[i]);    $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);    }    }</span>    //set attributes    jQuery(form).css('position', 'absolute');    jQuery(form).css('top', '-1200px');    jQuery(form).css('left', '-1200px');    jQuery(form).appendTo('body');      return form;    },
<pre name="code" class="javascript"> 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;        <span style="color:#ff0000;">var form = jQuery.createUploadForm(id, s.fileElementId, s.data);</span>        var io = jQuery.createUploadIframe(id, s.secureuri);        var frameId = 'jUploadFrame' + id;        var formId = 'jUploadForm' + id;  


3、文件成功上传,然而返回数据却进了error

因为ajaxfileupload的返回参数多了一串<pre>,无法用json格式解析,所以进了error

我的做法是修改了json返回值

 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" ){<span style="color:#ff0000;"><span style="white-space:pre"></span>var a = data.indexOf("{");        var b = data.indexOf("}")+1;        data = data.substring(a,b);        //alert(data);</span>            eval("data = " + data);        }                    // evaluate scripts within html        if( type == "html" ){         jQuery("<div>").html(data).evalScripts();        }                    return data;    }


4、ajaxfileupload携带参数传递中文乱码

因为ajaxfileload默认是以ISO-8859-1编码,所以在解析的request的时候要转换成你的编码格式

(用中文编码过滤器没有效果,不懂为什么,希望大神指教!!!)

for(FileItem file :files){String type = file.getContentType();if(type!=null) continue;if(file.isFormField()){//System.out.println(file.getFieldName());//System.out.println(file.getString());<span style="color:#ff0000;">if("painter".equals(file.getFieldName().trim())){painter = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");}if("picname".equals(file.getFieldName().trim())){picname = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");}if("userId".equals(file.getFieldName().trim())){userId = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");}</span>}}


5、有些ajaxfileupload.js中的post、json需要大写才能生效,版本太多,需要自己查看js文件


附上完整的ajaxfileupload上传文件代码

前台jsp

<span style="white-space:pre"></span><div class="modal-body"><div class="form-group"><label id="label1" class="col-sm-3 control-label">作品名称</label><div class="col-sm-8"><input type="text" class="form-control" id="input_picname"><span id="input_picname_msg"></span></div><label id="label2" class="col-sm-3 control-label">  作者</label><div class="col-sm-8"><input type="text" class="form-control" id="input_picpain"><span id="input_picpain_msg"></span></div><div class="col-sm-8"><input type="file" name="upfile" class="form-control" id="input_pic" /><span id="input_pic_msg"></span></div><!-- <div class="progress_bar"><span class="progress_per"></span></div> --></div></div>
js文件
function addpic() {var picname = $("#can #input_picname").val();var picpain = $("#can #input_picpain").val();var imgURL = $("#input_pic").val();$("#can #input_picname_msg").html("");$("#can #input_picpain_msg").html("");if (picname == "") {$("#can #input_picname_msg").html("作品名称不可为空");return;}if (picpain == "") {$("#can #input_picpain_msg").html("作者不可为空");return;}if (imgURL == ""){alert("请选择上传的图片");return ;}var suffix = imgURL.substr(imgURL.lastIndexOf(".")+1).toLowerCase();if(suffix!="jpg"&&suffix!="png"&&suffix!="gif"&&suffix!="bmp"&&suffix!="jpeg"){alert("请上传图片格式的文件");return ;}$.ajaxFileUpload({url:"savepic.do",type:"POST",secureuri:false,data:{painter:picpain,picname:picname,userId:userId,},fileElementId:'input_pic',dataType:"json",success:function(data,status){alert(data.msg);toHref("pictrue/toPictrue.do");},error:function(data, status, e){alert("图片上传失败,请检查网络后重试");}});}
服务器端Service

public MyResult savePic(HttpServletRequest req){MyResult result = new MyResult();//图片信息picItem item = new picItem();String painter = null;String picname = null;String userId = null;String picId = null;String fileName = null;Date time = null;String pictrue = null;boolean isMultipart = ServletFileUpload.isMultipartContent(req);DiskFileItemFactory factory = new DiskFileItemFactory();//ServletContext context = req.getSession().getServletContext();////设置临时文件存放地址//factory.setRepository(new File(System.getProperty("java.io.tmpdir")));ServletFileUpload upload = new ServletFileUpload(factory);try {//set request encoding//req.setCharacterEncoding("utf-8");//获取request中的信息//upload.parseRequest(req);//MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;//List<MultipartFile>files = mRequest.getFiles("file");//System.out.println(files.size());//for(MultipartFile file :files){List<FileItem> files = upload.parseRequest(req);//System.out.println(files);//System.out.println(files.size());for(FileItem file :files){String type = file.getContentType();if(type!=null) continue;if(file.isFormField()){//System.out.println(file.getFieldName());//System.out.println(file.getString());if("painter".equals(file.getFieldName().trim())){painter = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");}if("picname".equals(file.getFieldName().trim())){picname = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");}if("userId".equals(file.getFieldName().trim())){userId = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");}}}//System.out.println(new String(picname.getBytes("ISO-8859-1"),"utf-8"));for(FileItem file :files){String type = file.getContentType();if(type==null){continue;}picId = acgUtil.createId();time = new Date();String rootUrl = new SimpleDateFormat("yyyyMMdd").format(time);String name = new SimpleDateFormat("HHmmss").format(time);fileName = rootUrl+name+userId+".jpg";//获得文件储存路径String realPath = sc.getRealPath("/");realPath +="img/";realPath +=(rootUrl+"/");//创建文件目录File dir = new File(realPath);if(!dir.exists()){dir.mkdirs();}//创建文件对象File f = new File(realPath,fileName);if(f.exists()){f.delete();}//创建文件f.createNewFile();//file.transferTo(f);file.write(f);pictrue = "../img/"+rootUrl+"/"+fileName;//add pictrue message to mysqlitem.setPictrue(pictrue);item.setPainter(painter);item.setPicname(picname);item.setPictime(new Timestamp(time.getTime()));item.setPic_id(picId);item.setSubuser_id(userId);picDao.savePic(item);}} catch (Exception e) {e.printStackTrace();throw new RuntimeException("图片上传失败",e);}result.setStatus(0);result.setMsg("图片上传成功");return result;}






0 0
原创粉丝点击