由于我们项目的jsp也页面访问后台都是无form的,统统都是ajax异步提交参数数据,所以我就百度着通过ajaxfileupload.js插件实现了

 

 

1.前台代码

  

<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
<script type="text/javascript">
    function ajaxFileUpload() {
        $.ajaxFileUpload({
            url : 'upload',
            secureuri : false,
            fileElementId : 'fileToUpload',
            dataType : 'json',
            data : {username : $("#username").val()},
            success : function(data, status) {
            },
            error : function(data, status, e) {
                alert('上传出错');
            }
        })

        return false;

    }
</script>
</head>

<body>
    <h1>选择图片后,点击按钮上传</h1>
    <input id="fileToUpload" type="file" size="45" name="fileToUpload"
        class="input">
    <button class="button" onclick="ajaxFileUpload()">上传</button>
    <br>
</body>

ps:  需要注意ajax的fileElementId的值对应文件域的id和name;

  插件本身不支持多文件上传,但我们项目的需求是多文件上传的,所以我百度了好久修改了插件最终支持了,修改后的插件源码见文章最后:

修改后的ajax  fileElementId参数
这样即可多文件上传:(image1,和image2两个文件域)

fileElementId:['image1','image2'], //文件域id值 name值

 

2.我们项目没有框架所以我贴下servlet的后台接收(全贴了,有啰嗦的地方大家见谅,自己删除吧)

String img_path = request.getSession().getServletContext().getRealPath("/");
        String p = "huiy";// 作为一个标志符,如果p不等于1,则图片命名为pkey_(n++),否则随机生成
        Map<String, Object> filenamemap = FileUploadUtil.upload(request,img_path, "image",p);

 

public static Map<String, Object> upload(HttpServletRequest request,String path,String type, String p) {
        // 最大文件大小
        //long maxSize = 1048576;// 1M=1024kb(千字节)=1048576b字节
        boolean flag = true;
        String pkey = "";
        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
        path=path+type;
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<String> filenamelist = new ArrayList<String>();
        try {
            List<FileItem> list = upload.parseRequest(request);
            int n = 1;
            for (FileItem item : list) {
                // 如果获取的 表单信息是普通的 文本 信息
                if (item.isFormField()) {// 判断是否是普通文本
                    String name = item.getFieldName(); // 获取上传时候的data数据(普通数据)
                    String value = item.getString();
                    if ("pkey".equals(name)) {
                        pkey = value;
                    }
                } else {
                    /*
                     * // 检查文件大小 if (item.getSize() > maxSize) { continue; }
                     */
                    /**
                     * 以下三步,主要获取 上传文件的名字
                     */
                    // 获取图片名
                    String fileName = item.getName();
                    // 检查扩展名
                    String fileExt = fileName.substring(
                            fileName.lastIndexOf(".") + 1).toLowerCase();
                    if (!Arrays.<String> asList(extMap.get("image").split(","))
                            .contains(fileExt)) {
                        continue;
                    }

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String base64Name = df.format(new Date()) + "_"
                            + new Random().nextInt(1000);
                    if (!"1".equals(p)) {
                        base64Name = p + pkey + "_" + n;
                    }
                    String filename = base64Name + "." + fileExt;
                    OutputStream out = new FileOutputStream(new File(path,
                            filename));

                    InputStream in = item.getInputStream();

                    int length = 0;
                    byte[] buf = new byte[1024];

                    while ((length = in.read(buf)) != -1) {
                        out.write(buf, 0, length);
                    }

                    in.close();
                    out.close();
                    filenamelist.add(type+"/"+filename);
                    n++;
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag", flag);
        map.put("pkey", pkey);
        map.put("filenamelist", filenamelist);
        return map;
    }

 3.页面访问图片

  由于本地图片上传到了本地服务器所以本地访问时为:

  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();加上图片的路径

 

ps: ①ajaxfileupload.js 的本质是先创建个form表单,提交后再把表单删除。

    ②ajaxfileupload.js 网上下载的插件有很多错误,需要修正

 

 附带我修改后的插件(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(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, 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>'); 
  var oldElement = jQuery('#' + fileElementId);
  var newElement = jQuery(oldElement).clone();
  jQuery(oldElement).attr('id', fileId);
  jQuery(oldElement).before(newElement);
  jQuery(oldElement).appendTo(form);
  
  //add data
  if(data) { 
    for (var i in data) { 
        $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').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.id;        
        //var id = s.fileElementId;        
        var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
        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 ){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);
        }   */
        jQuery('#' + frameId).load(uploadCallback);
        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" ){
            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);  
        }
            
        // evaluate scripts within html
        if( type == "html" ){
         jQuery("<div>").html(data).evalScripts();
        }
            
        return data;
    },
    /*handleError: function( s, xml, status, e ) {
        // If a local callback was specified, fire it
        if ( s.error )
            s.error( xml, status, e );

        // Fire the global callback
        if ( s.global )
            jQuery.event.trigger( "ajaxError", [xml, s, e] );
    }*/
    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] );
        }
    }
});