不使用form進行上傳文件圖片,使用jQuery上傳文件圖片

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] );
        }
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章