天天看點

IE8異步上傳附件(主要代碼)

1.jsp檔案

   引入檔案

        <script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>

        <script type="text/javascript" src="../js/jquery.upload2.js"></script>

     <style type="text/css">

        .file-box{ position:relative;width:340px} 

        .txt{ height:22px; border:1px solid #cdcdcd; width:200px;border-right:none;} 

        .btn{ background-color:#FFF; border:1px solid #CDCDCD;height:26px; width:70px;} 

        .file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity=0);opacity: 0;width:260px }

    </style>

    <div class="file-box">

            <input type='text' name='textfield' id='textfield' class='txt' /> 

            <input type='button' class='btn' value='浏覽...' /> 

            <input type="file" name="fileField" class="file" id="fileField" size="28" οnchange="document.getElementById('textfield').value=this.value" /> 

            <input type="submit" name="submit" class="btn" value="上傳" οnclick="doUpdateFile()"/> 

        </div>

    <script type="text/javascript">   

        function doUpdateFile(){

            $("input[name=fileField]").upload({   

                url: '../AttachmentReceiver',            

                params: {},       

                // 上傳完成後, 傳回json, text           

                onSend: function (obj, str) { 

                    return true; 

                },     

                // 上傳之後回調      

                onComplate: function (data) {         

                    alert(data);     

                }   

            });    

            $("input[name=fileField]").upload("ajaxSubmit");

        }

    </script>

2.jquery.upload2.js

(function ($) {

    var frameCount = 0;

    var formName = "";

    var iframeObj = null;

    var state = {};

    //var fileHtml = "";

    var colfile = null;

    //清空值

    function clean(target) {

        var file = $(target);

        var col = file.clone(true).val("");

        file.after(col);

        file.remove();

    //關鍵說明

    //先得到目前的對象和參數,接着進行克隆(同時克隆事件)

    //将克隆好的副本放在原先的之後,按照順序逐個删除,最後初始化克隆的副本

    };

    function h5Submit(target) {

        var options = state.options;

        var fileObj = target[0].files[0];

        var fd = new FormData();//h5對象

        //附加參數

        for (key in options.params) {

            fd.append(key, options.params[key])

        }

        var fileName = target.attr('name');

        if (fileName == ''

            || fileName == undefined) {

            fileName = 'file';

        }

        fd.append(fileName, fileObj);

        //異步上傳

        var xhr = new XMLHttpRequest();

        xhr.upload.addEventListener("progress", function (evt) {

            if (evt.lengthComputable) {

                var percentComplete = Math.round(evt.loaded * 100 / evt.total);

                console.log(percentComplete + "%");

                if (options.onProgress) {

                    options.onProgress(evt);

                }

            }

        }, false);

        xhr.addEventListener("load", function (evt) {

            if ('json' == options.dataType) {

                var d = window.eval('(' + evt.target.responseText + ')');

                options.onComplate(d);

            } else {

                options.onComplate(evt.target.responseText);

            }

        }, false);

        xhr.addEventListener("error", function () {

            console.log("error");

        }, false);

        xhr.open("POST", options.url);

        xhr.send(fd);

    }

    function ajaxSubmit(target) {

        var options = state.options;

        if (options.url == '' || options.url == null) {

            alert("無上傳位址");

            return;

        }

        if ($(target).val() == '' || $(target).val() == null) {

            alert("請選擇檔案");

            return;

        }

        var canSend = options.onSend($(target), $(target).val());

        if (!canSend) {

            return;

        }

        if (window.FormData) {

            //h5

            console.log('h5Submit');

            h5Submit(target);

        } else {

            if (iframeObj == null) {

                var iframe; 

                try { // for I.E.

                    iframe = document.createElement('<iframe name="fileUploaderEmptyHole" style="position:absolute;top:-8888px">'); 

                } catch (ex) { //for other browsers, an exception will be thrown

                    iframe = document.createElement('iframe'); 

                }

                iframe.id = 'fileUploaderEmptyHole';

                iframe.name = 'fileUploaderEmptyHole';

                iframe.width = 0;

                iframe.height = 0;

                iframe.marginHeight = 0;

                iframe.marginWidth = 0;

                iframe = $(iframe);

                var frameName = 'upload_frame_' + (frameCount++);

                //var iframe = $('<iframe style="position:absolute;top:-9999px" ><script type="text/javascript"></script></iframe>').attr('name', frameName);

                formName = 'form_' + frameName;

                var form = $('<form method="post" style="display:none;" enctype="multipart/form-data"/>').attr('name', formName);

                form.attr("target", 'fileUploaderEmptyHole').attr('action', options.url);

                //

                var fileHtml = $(target).prop("outerHTML");

                colfile = $(target).clone(true);

                $(target).replaceWith(colfile);

                var formHtml = "";

                // form中增加資料域

                for (key in options.params) {

                    formHtml += '<input type="hidden" name="' + key + '" value="' + options.params[key] + '">';

                }

                form.append(formHtml);

                form.append(target);

                iframe.appendTo("body");

                form.appendTo("body");

                iframeObj = iframe;

            }

            //禁用

            $(colfile).attr("disabled", "disabled");

            var form = $("form[name=" + formName + "]");

            var fm1=window.frames['fileUploaderEmptyHole']; 

            var fmState=function(){   

                var state=null;   

                if(document.readyState){     

                    try{       

                        state=fm1.document.readyState;    

                    }catch(e){

                        state=null;

                    }     

                    if(state=="complete" || !state){//loading,interactive,complete  

                        alert(state);

                        var contents = fm1.document;

                        alert(contents);

                        var data = $(contents).contents().find('body').text();

                        options.onComplate(data);

                        iframeObj.remove();

                        form.remove();

                        iframeObj = null;

                        //啟用

                        $(colfile).removeAttr("disabled");      

                        return;    

                    }     

                    window.setTimeout(fmState,10);  

                }

            };

            //在改變src或者通過form target送出表單時,執行語句: 

            if(fmState.TimeoutInt) 

                window.clearTimeout(fmState.timeoutInt); 

            fmState.timeoutInt = window.setTimeout(fmState,400);

            try {

                alert(1);

                form.submit();

            } catch (Eobject) {

                console.log(Eobject);

            }

        }

    };

    //構造

    $.fn.upload = function (options) {

        if (typeof options == "string") {

            return $.fn.upload.methods[options](this);

        }

        options = options || {};

        state = $.data(this, "upload");

        if (state)

            $.extend(state.options, options);

        else {

            state = $.data(this, "upload", {

                options: $.extend({}, $.fn.upload.defaults, options)

            });

        }

    };

    //方法

    $.fn.upload.methods = {

        clean: function (jq) {

            return jq.each(function () {

                clean(jq);

            });

        },

        ajaxSubmit: function (jq) {

            return jq.each(function () {

                ajaxSubmit(jq);

            });

        },

        getFileVal: function (jq) {

            return jq.val()

        }

    };

    //預設項

    $.fn.upload.defaults = $.extend({}, {

        url: '',

        dataType: 'json',

        params: {},

        onSend: function (obj, str) {

            return true;

        },

        onComplate: function (e) {},

        onProgress: function (e) {}

    });

})(jQuery);

3.servlet代碼 AttachmentReceiver

public class AttachmentReceiver extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        try {

        // Check that we have a file upload requestss  

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {

            return;

        }

        response.setContentType("text/html;charset=UTF-8");

        //讀取請求Body

        byte[] body = readBody(request);

        //取得所有Body内容的字元串表示

        String textBody = new String(body, "ISO-8859-1");

        //取得上傳的檔案名稱

        String fileName = getFileName(textBody);

        if (fileName.indexOf(".") != -1) {

            fileName = fileName.substring(fileName.lastIndexOf("."));

        }else{

            fileName =".doc";

        } 

        //檔案名稱

        String format = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());

        //檔案夾日期

        String dirFormat = new SimpleDateFormat("yyyyMMdd").format(new Date());

       //磁盤名稱

        String fileDist = "e:";

        //磁盤路徑

        String filePath = "/resource/attachments/mjcrt"+dirFormat+"/";

        checkFilePath(fileDist+filePath);

        String requestPath="/resource/attachments/mjcrt"+dirFormat+"/";

        String path=requestPath + format + fileName;

        fileName = fileDist + filePath + format + fileName;

        //取得檔案開始與結束位置

        Position p = getFilePosition(request, textBody);

        //輸出至檔案

        writeTo(fileName, body, p);

        out.print(path);

        } finally {            

            out.close();

        }

    }

    private void checkFilePath(String filePath) throws IOException{

        File f = new File(filePath);

        if(!f.exists()){

         f.mkdirs();

        }

    }

    class Position {

        int begin;

        int end;

        public Position(int begin, int end) {

            this.begin = begin;

            this.end = end;

        }

    }

    private byte[] readBody(HttpServletRequest request) throws IOException {

        //擷取請求文本位元組長度

        int formDataLength = request.getContentLength();

        //取得ServletInputStream輸入流對象

        DataInputStream dataStream = new DataInputStream(request.getInputStream());

        byte body[] = new byte[formDataLength];

        int totalBytes = 0;

        while (totalBytes < formDataLength) {

            int bytes = dataStream.read(body, totalBytes, formDataLength);

            totalBytes += bytes;

        }

        return body;

    }

    private Position getFilePosition(HttpServletRequest request, String textBody) throws IOException {

        //取得檔案區段邊界資訊

        String contentType = request.getContentType();

        String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());

        //取得實際上傳檔案的氣勢與結束位置

        int pos = textBody.indexOf("filename=\"");

        pos = textBody.indexOf("\n", pos) + 1;

        pos = textBody.indexOf("\n", pos) + 1;

        pos = textBody.indexOf("\n", pos) + 1;

        int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;

        int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;

        int end = ((textBody.substring(0, boundaryLoc)).getBytes("ISO-8859-1")).length;

        return new Position(begin, end);

    }

    private String getFileName(String requestBody) {

        String fileName = requestBody.substring(requestBody.indexOf("filename=\"") + 10);

        fileName = fileName.substring(0, fileName.indexOf("\n"));

        fileName = fileName.substring(fileName.indexOf("\n") + 1, fileName.indexOf("\""));

        return fileName;

    }

    private void writeTo(String fileName, byte[] body, Position p) throws IOException {

        FileOutputStream fileOutputStream = new FileOutputStream(fileName);

        fileOutputStream.write(body, p.begin, (p.end - p.begin));

        fileOutputStream.flush();

        fileOutputStream.close();

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        processRequest(request, response);

    }

    @Override

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        processRequest(request, response);

    }

    @Override

    public String getServletInfo() {

        return "Short description";

    }// </editor-fold>

}