简体   繁体   English

在获取python cgi脚本以打开从AJAX传递给它的文件时遇到问题

[英]having problems getting a python cgi script to open file passed to it from AJAX

In a prior post I was trying to upload a file to a server using HTML and Javascript. 在先前的文章中,我试图使用HTML和Javascript将文件上传到服务器。 I ran into several problems with my implementation so I've taken a different approach. 我在实现过程中遇到了几个问题,因此我采用了不同的方法。 I have a HTML form and a python script in the cgi directory of my webserver. 我的网络服务器的cgi目录中有HTML表单和python脚本。 Here is my HTML code... 这是我的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>

I am using AJAX because it occured to me that my cgi script could take up to a couple of minutes to run depending on the file the user enters. 我之所以使用AJAX,是因为我想到我的cgi脚本可能要花几分钟才能运行,具体取决于用户输入的文件。 What I'm trying to do is get the contents of the file passed to my python CGI script and print them out on the page. 我想做的是将文件内容传递给python CGI脚本,并在页面上打印出来。 All I'm getting is "C:\\fakepath\\. What I want to do is get the file contents. Here is my cgi script... 我得到的只是“ 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'

Also should I be using 我也应该使用

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

instead of 代替

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

I tried both but the POST one doesn't even return the name of my file. 我都尝试过,但是POST甚至都没有返回文件名。 Also it occured to me that I read that I may not even need the tags in my script since I submit this information using javascript. 我也发现我读到我可能甚至不需要脚本中的标签,因为我使用javascript提交了此信息。 Is this true. 这是真的。 My page seems to work without the form tags (at least on Chrome and Firefox). 我的页面似乎没有表单标签即可运行(至少在Chrome和Firefox上)。

If you examine the variable file using console.log(), you will notice that it only contains the filename and not its contents. 如果使用console.log()检查变量文件 ,您会注意到它仅包含文件名而不包含其内容。

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

The standard way to upload a file via AJAX is to use an iframe. 通过AJAX上传文件的标准方法是使用iframe。 The following code is taken from jquery.extras.js and is based on malsup's form plugin . 以下代码取自jquery.extras.js并基于malsup的form plugin

<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>

Your CGI code is fine. 您的CGI代码很好。 However, I highly recommend using a web framework like Pyramid or Django for your own sanity. 但是,我强烈建议您使用PyramidDjango之类的Web框架,以保持自己的理智。

#!/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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM