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

标签 python html cgi bioinformatics

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

这是我上传文件的 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,)

所以输出是:'没有文件被上传'。问题是测试 if fileitem.filename: 总是呈现 None 因为 fileitem 是 MiniFieldStorage('file', 'Acinetobacter_pittii_protein. faa') 当我上传一个名为 Acinetobacter_pittii_protein.faa 的文件时

我正在为 Linux 使用 Ubuntu 16.04 LTSXAMPP 7.1.10

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

我真的很感激任何帮助! :)

最佳答案

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

关于python - 如何使用python cgi从html表单上传文件到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49734694/

相关文章:

python - Python 中的特殊字符

Python语法。美丽,正确,简短的代码

javascript根据窗口高度设置左侧绝对位置

html - 定位:after-pseudo behind text in a link

windows - 当客户端在下载过程中关闭网页时,Perl cgi 脚本仍在运行

python - 仅当新列表的第一项唯一时才扩展列表列表

python - Visual Studio 代码;如何并排打开两个Python shell

python - 如何抓取特定区域的产品价格

html - 如何使用 DateTime 对象执行函数?

php - 如何最有效地将数据从网页输入到Python脚本