如何使用shift / ctrl + Python + CGI

时间:2017-06-06 13:21:33

标签: html5 python-3.x cgi

我按照以下指南介绍了如何使用HTML和CGI https://www.tutorialspoint.com/python3/python_cgi_programming.htm将文件上传到我的服务器。

它工作得很好但是,我需要用户一次添加大量文件。理想情况下,我希望他们按住“SHIFT”或“CTRL”并选择他们想要上传的文件。这可能吗?

这就是我的工作原理。

HTML

<!doctype html>
<html>
<head>
<title>testupload</title>
</head>
<body>

 <form enctype="multipart/form-data"
                     action="logsupload.py" method="post">
   <p>File: <input type="file" name="filename" /></p>
   <p><input type="submit" value="Upload" /></p>
   </form>


</body>

</html>

Python脚本

 #!\Users\administrator\Python\Python36-32\python.exe -u

    import cgi, os
    import cgitb; cgitb.enable()

    form = cgi.FieldStorage()

    # Get filename here.
    fileitem = form['filename']

    print("""\
    Content-Type: text/html\n
    <html>
    <body>

    """)
    # Test if the file was uploaded
    if fileitem.filename:
        # strip leading path from file name to avoid
        # directory traversal attacks
        fn = os.path.basename(fileitem.filename)
        open('C:/testupload/' + fn, 'wb').write(fileitem.file.read())

        print('The file "' + fn + '" was uploaded successfully')

    else:
        print("No file was uploaded")

    print("""  
    <form name="pyform" method="GET" action="nextscript.py" >

        Enter your favorite dog breed
      <input type="text" name="breed"/>
        <br>


      <input type="submit" name="submit" value="Submit" />

    </form>

    """)

1 个答案:

答案 0 :(得分:0)

这就是诀窍。

HTML

<form enctype="multipart/form-data" action="upload.py" method="post">
     <p>File: <input type="file" name="filename" multiple=""/>
<p><input type="submit" value="Next" /></p>
   </form>

import shutil
import cgi, os


print("""\
Content-Type: text/html\n
<html>
<body>

""")
directory = 'C:/tmp/'

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

if 'filename' in form:

   filefield = form['filename']
   if not isinstance(filefield, list):
      filefield = [filefield]

   for fileitem in filefield:

       if fileitem.filename:
          fn = os.path.basename(fileitem.filename)
          # save file
          with open(directory + fn, 'wb') as f:
              shutil.copyfileobj(fileitem.file, f)

print("""
 </body>
</html>
""")