在从AJAX传递文件时,python cgi脚本无法打开该文件

1 投票
1 回答
2169 浏览
提问于 2025-04-17 09:05

在之前的一篇帖子中,我尝试用HTML和JavaScript把一个文件上传到服务器。但是在实现过程中遇到了几个问题,所以我换了个方法。我现在有一个HTML表单和一个放在我网页服务器的cgi目录下的Python脚本。以下是我的HTML代码...

<html>
<head>
<script type="text/javascript">
    function loadXMLDoc(){
        var xmlhttp;
        if (window.XMLHttpRequest){
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else{
            // code for IE6, IE5 seriously, why do I bother?
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                    document.getElementById("outputDiv").innerHTML=xmlhttp.responseText;
                }
        }
        var file = document.getElementById('idexample').value;
        xmlhttp.open("GET","/cgi/ajax.py?uploadFile="+file,true);
        xmlhttp.send();
    }
</script>
</head>

<body onload="changeInput()">
<form name = "form_input" enctype="multipart/form-data" method="POST">
    <input type="file" ACCEPT="text/html" name="uploadFile" id="idexample" />
    <button type="button" onclick="loadXMLDoc()">Enter</button>
</form>
<div id="outputDiv"></div>
</body>
</html>

我使用AJAX是因为我想到我的cgi脚本可能需要几分钟才能运行,具体取决于用户输入的文件。我想做的是把文件的内容传递给我的Python CGI脚本,然后在页面上打印出来。但我现在得到的只是"C:\fakepath\"。我想要的是文件的具体内容。以下是我的cgi脚本...

#!/usr/bin/python
import cgi

form = cgi.FieldStorage()
print 'Content-Type: text/html\n'
if form.has_key('uploadFile'):
    print str(form['uploadFile'].value)
else:
    print 'no file'

另外,我应该使用

xmlhttp.open("POST","/cgi/ajax.py",true); 

而不是

xmlhttp.open("GET","/cgi/ajax.py?uploadFile="+file,true);

我试过这两种方法,但POST的那个甚至没有返回我的文件名。而且我想到我之前看到过,可能在我的脚本中根本不需要这些

标签,因为我用JavaScript提交这些信息。这个说法是真的吗?我的页面在没有标签的情况下似乎也能正常工作(至少在Chrome和Firefox上是这样的)。

1 个回答

1

如果你用console.log()来查看变量file,你会发现它只包含文件名,而不包含文件的内容。

var file = document.getElementById('idexample').value;
console.log(file); // Outputs filename

通过AJAX上传文件的标准方法是使用iframe。下面的代码来自于jquery.extras.js,它是基于malsup的表单插件

<html>
<body>

<form id=input action=/cgi/ajax.py method=post>
    <input type=file name=uploadFile>
    <input type=submit value=Submit>
</form>

<div id=output></div>

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
    $.fn.ajaxForm = function(options) {
        options = $.extend({}, {
            onSubmit:function() {},
            onResponse:function(data) {}
        }, options);
        var iframeName = 'ajaxForm', $iframe = $('[name=' + iframeName + ']');
        if (!$iframe.length) {
            $iframe = $('<iframe name=' + iframeName + ' style="display:none">').appendTo('body');
        }
        return $(this).each(function() {
            var $form = $(this);
            $form
                .prop('target', iframeName)
                .prop('enctype', 'multipart/form-data')
                .prop('encoding', 'multipart/form-data')
                .submit(function(e) {
                    options.onSubmit.apply($form[0]);
                    $iframe.one('load', function() {
                        var iframeText = $iframe.contents().find('body').text();
                        options.onResponse.apply($form[0], [iframeText]);
                    });
                });
        });
    };
    $('#input').ajaxForm({
        onResponse:function(data) {
            $('#output').html(data);
        }
    });
</script>

</body>
</html>

你的CGI代码是没问题的。不过,我强烈建议你使用像PyramidDjango这样的网络框架,这样会让你更轻松。

#!/usr/bin/python
import cgi

form = cgi.FieldStorage()
print 'Content-Type: text/html\n'
if 'uploadFile' in form and form['uploadFile'].filename:
    print form['uploadFile'].value
else:
    print 'no file'

撰写回答