bigbone 2008-10-24 13:16
浏览 414
已采纳

动态form提交file不能提交

通过javascript的dom动态生成form,在form表单中添加file。后台通过servlet实现文件的上传,在ff下能顺利提交,在IE不能能提交,但能得到文件的名称,就是通过request.getInputStream()时得不到流。在body下写form表单,通过document.getElementById()向form表单内添加file能够实现上传。不知道是为什么?请赐教。 :wink:
代码如下:
[code="java"]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">



Insert title here
function createform() { var uploadForm =document.createElement("form"); uploadForm.setAttribute("id","1id"); uploadForm.setAttribute("method","post"); uploadForm.setAttribute("enctype","multipart/form-data"); uploadForm.setAttribute("target","iframeName"); uploadForm.setAttribute("action","<%=request.getContextPath() %>/upload"); var Iframe=document.createElement("div"); Iframe.innerHTML="<iframe name=iframeName>"; document.body.appendChild(uploadForm); document.body.appendChild(Iframe); document.getElementById("1id").appendChild(document.getElementById("files")); } function uploadSubmit() { alert(document.getElementById("files").name); alert(document.getElementById("1id").innerHTML); document.getElementById("1id").submit(); } function upload() { document.getElementById("test").submit(); } function setFileToForm() { var file=document.getElementById("test1"); document.body.removeChild(file); document.getElementById("uploadtest").appendChild(file); alert(document.body.innerHTML); } function submitUpload() { document.getElementById("uploadtest").submit(); }








[/code]
servlet没有问题,已测试过!

  • 写回答

1条回答 默认 最新

  • iteye_20231 2008-10-24 16:56
    关注

    原因肯定有,不过如果你用jQuery Form Plugin的话就可以很安逸的使用了.
    http://plugins.jquery.com/project/form
    里面有提交file的代码,不怕麻烦的话抠出来里面的fileUpload()函数就行了.顺便贴出来
    不过细节要你自己改了.
    function fileUpload() {
    var form = $form[0];
    var opts = $.extend({}, $.ajaxSettings, options);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];
        var op8 = $.browser.opera && window.opera.version() < 9;
        if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
    
        var xhr = { // mock object
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };
    
        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);
    
        var cbInvoked = 0;
        var timedOut = 0;
    
        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });
    
            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
    
            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
    
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);
    
        function cb() {
            if (cbInvoked++) return;
    
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
    
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;
                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };
    
                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }
    
            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
    
            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };
    
        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题