简体   繁体   English

如何使用Python / CGI进行文件上传

[英]How to use Python/CGI for file uploading

I'm trying to make a file uploader page that will prompt the user for a file and will upload while displaying progress. 我正在尝试创建一个文件上传页面,它会提示用户输入文件,并在显示进度时上传。

At the moment I've managed to make a simple HTML page that can calls my python script. 目前我已经设法创建一个可以调用我的python脚本的简单HTML页面。 The python script will then get the file and upload in 1000 byte chunks. 然后python脚本将获取文件并以1000字节的块上传。

I have two main problem (mainly due to be completely new to this): 我有两个主要问题(主要是由于对此全新):

1) I can't get the file size to calculate percentage 2) I don't know how to communicate between the server side python and whatever is in the page to update the progress status;presumably javascript. 1)我无法获得文件大小来计算百分比2)我不知道如何在服务器端python和页面中的任何内容之间进行通信以更新进度状态;大概是javascript。

Am I going about everything the wrong way? 我是否会采取错误的方式? Or is there a solution to my woes? 或者我的困境有解决方案吗?

Here is my python code: 这是我的python代码:

#!/usr/local/bin/python2.5 
import cgi, os
import cgitb; cgitb.enable()

try:
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) 
    msvcrt.setmode (1, os.O_BINARY) 

except ImportError:
    pass

form = cgi.FieldStorage()
upload = form['file']

if upload.filename:
    name = os.path.basename(upload.filename)
    out = open('/home/oetzi/webapps/py/' + name, 'wb', 1000)
    message = "The file '" + name + "' was uploaded successfully"

    while True:
        packet = upload.file.read(1000)
        if not packet:
            break
        out.write(packet)
    out.close()
else:

message = "Derp... could you try that again please?"

print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)

This is more complex than it seems, given how file uploading works in the HTTP protocol. 考虑到文件上传如何在HTTP协议中工作,这比看起来更复杂。 Most web servers will give control to the CGI script only when the uploaded file has been completely transferred, so there's no way to give feedback in the meanwhile. 大多数Web服务器只有在上传文件完全传输后才能控制CGI脚本,因此同时无法提供反馈。

There are some Python libraries that attempt to tackle this issue, though. 但是,有些Python库试图解决这个问题。 For example: gp.fileupload (works with WSGI, not CGI). 例如: gp.fileupload (与WSGI一起使用,而不是CGI)。

The trick is to provide a way to query the upload progress via AJAX while still transferring the uploaded file. 诀窍是提供一种方法,通过AJAX查询上传进度,同时仍然传输上传的文件。 This is of no use if the web server (for example, Apache or nginx) is not configured to support the upload progress feature because you will probably see a 0% to 100% jump in the progress bar. 如果Web服务器(例如,Apache或nginx)未配置为支持上载进度功能,则没有用,因为您可能会在进度条中看到0%到100%的跳转。

I suggest you try Plupload , which works on the client-side and is much simpler. 我建议你试试Plupload ,它在客户端工作,而且更简单。

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

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