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

2024-04-19 19:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个生物信息学的学生,我有一个问题从一个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>

这是爆炸的一部分_解析器.cgi我正在使用将文件上载到服务器:

^{pr2}$

所以输出是:“没有上传任何文件”。问题是如果文件项.文件名:呈现None总是因为fileitem是MiniFieldStorage('file','Acinetobacter_pittii)_蛋白质.faa')当我上传一个名为pittii不动杆菌的文件时_蛋白质.faa在

我在Linux上使用的是Ubuntu16.04LTS和XAMPP7.1.10。在

我只想把文件上传到服务器上,这样我就可以处理它了。我不知道你是否需要剩下的代码,我没有把它们都放进去,因为它们很长。在

我真的很感谢你的帮助!:)


Tags: 文件orgbr脚本httpinputhtmlwww
1条回答
网友
1楼 · 发布于 2024-04-19 19:22:41

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

相关问题 更多 >