如何使用 python cgi 从 html 表单上传文件到服务器

How to upload files to server from html form using python cgi

我是一名生物信息学学生,我在从 html 脚本上传文件时遇到问题。我尝试使用在互联网上找到的不同模板,但无法解决我在该网站上搜索其他主题的问题。

这是我用于上传文件的 html 表单脚本的片段:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<BR>
<CENTER><FORM ACTION="blast_parser.cgi" METHOD="POST" ENCTYPE="multipart/form-data">

<FONT SIZE=+1>Upload your sequence(s) file</FONT>

<BR><INPUT TYPE="file"  NAME= "file" ID="file">
<BR>
<BR>
<INPUT TYPE="submit" VALUE="BLAST!" NAME="submit" ID="submit">
<input type="reset" value="Clear Form"><br>
<BR>
<BR>

这是 blast_parser.cgi 的一部分,我用来将文件上传到服务器:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cgi, os
import cgitb; cgitb.enable()
import glob, subprocess, shlex, sys, re

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

def fbuffer(f, chunk_size=10000):
    while True:
        chunk = f.read(chunk_size)
        if not chunk: break
        yield chunk

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

if fileitem.filename:
    fn = os.path.basename(fileitem.filename)
    f = open('/opt/lampp/htdocs/server_v1/uploads/' + fn, 'wb', 10000)
    for chunk in fbuffer(fileitem.file):
        f.write(chunk)
    f.close()
    message = 'The file "' + fn + '" was uploaded successfully'
else:
    message = 'No file was uploaded'

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

所以输出是:'No file was uploaded'。问题是 测试 if fileitem.filename: 总是呈现 None 因为 fileitem 是 MiniFieldStorage('file', 'Acinetobacter_pittii_protein.faa') 当我上传一个名为 Acinetobacter_pittii_protein.faa

的文件时

我正在使用 Ubuntu 16.04 LTSXAMPP 7.1.10 for Linux.

我只想将文件上传到服务器以便我可以处理它。我不知道你是否需要其余的代码,我没有把它们全部放出来,因为它们很长。

如果能提供帮助,我将不胜感激! :)

在Python中确实也很容易。

有关完整示例,请参阅下面的示例脚本 (python3)。代码由注释记录。如果您需要进一步说明,请询问:)

#!/usr/bin/python3
# Import Basic OS functions
import os
# Import modules for CGI handling
import cgi, cgitb, jinja2
import urllib.request

# enable debugging
cgitb.enable()
# print content type
print("Content-type:text/html\r\n\r\n")


# HTML INPUT FORM
HTML = """
<html>
<head>
<title></title>
</head>
<body>

  <h1>Upload File</h1>
  <form action="sendEx1.py" method="POST" enctype="multipart/form-data">
    File: <input name="file" type="file">
    <input name="submit" type="submit">
</form>

{% if filedata %}

<blockquote>

{{filedata}}

</blockquote>

{% endif %}  

</body>
</html>
"""


inFileData = None

form = cgi.FieldStorage()

UPLOAD_DIR='uploads'

# IF A FILE WAS UPLOADED (name=file) we can find it here.
if "file" in form:
    form_file = form['file']
    # form_file is now a file object in python
    if form_file.filename:

        uploaded_file_path = os.path.join(UPLOAD_DIR, os.path.basename(form_file.filename))
        with open(uploaded_file_path, 'wb') as fout:
            # read the file in chunks as long as there is data
            while True:
                chunk = form_file.file.read(100000)
                if not chunk:
                    break
                # write the file content on a file on the hdd
                fout.write(chunk)

        # load the written file to display it
        with open(uploaded_file_path, 'r') as fin:
            inFileData = ""
            for line in fin:
                inFileData += line


headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}

print(jinja2.Environment().from_string(HTML).render(filedata=inFileData))