html文件上传和python cgi

时间:2015-03-09 16:06:37

标签: jquery python ajax

我试图将文件上传到我的' / uploads'使用python uploader而不是php的this guide目录(所以我可以用我理解的语言进行一些重命名和花哨的预处理。)

所以我有模板index.html,表单本身如下:

<form id="upload" method="post" action="upload.py" enctype="multipart/form-data">
            <div id="drop">
                Drop Files Here

                <a>Browse</a>
                <input type="file" name="upl" multiple />
            </div>

            <ul>
                <!-- The file uploads will be shown here -->
            </ul>
        </form>

和python cgi脚本看起来像:

#!/usr/bin/env python
import cgi, os
import cgitb
import logging
try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode(0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode(1, os.O_BINARY) # stdout = 1
except ImportError:
    pass
cgitb.enable()
logging.basicConfig(filename='cgi.log',level=logging.DEBUG)
logging.info('log created')

def fbuffer(f, chunk_size=10000):
    """Generator to buffer file chunks"""
    while True:
        chunk = f.read(chunk_size)
        if not chunk: 
            break
        yield chunk

form = cgi.FieldStorage()

# A nested FieldStorage instance holds the file
if 'file' in form:
    filefield = form['file']
    if not isinstance(filefield, list):
        filefield = [filefield]
else:
    logging.debug('no file found')

# Test if the file was uploaded
for fileitem in filefield:
    if fileitem.filename:
        fn = os.path.basename(fileitem.filename) # strip leading path from file name to avoid directory traversal attacks
        if fn.split('.')[-1].lower() in ['png', 'jpg', 'gif','zip']:
            with open('uploads/' + fn, 'wb', 10000) as f:
                # Read the file in chunks
                for chunk in fbuffer(fileitem.file):
                  f.write(chunk)
            print '{"status":"success"}'
        else:
            print '{"status": "error"}'

    else:
        print '{"status":"error"}'

但是,没有任何内容写入&#39;上传&#39;,没有创建日志,cgitb.enable()没有做我能看到的任何事情!我不知道从哪里开始。如何调试无法输出任何内容的内容? 我尝试模仿的原始PHP代码是:

<?php

// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');

if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
        echo '{"status":"success"}';
        exit;
    }
}

echo '{"status":"error"}';
exit;

0 个答案:

没有答案