使用 CherryPy 上传文件

这个例子由三部分组成:

  • server.py - 可以接收和保存文件的 CherryPy 应用程序。
  • webpage.html - 如何从网页上传文件到 server.py 的示例。
  • cli.py - 如何从命令行工具将文件上载到 server.py 的示例。
  • Bonus - upload.txt - 你要上传的文件。

server.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import cherrypy

config = {
    'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080
    }
}

class App:

    @cherrypy.expose
    def upload(self, ufile):
        # Either save the file to the directory where server.py is
        # or save the file to a given path:
        # upload_path = '/path/to/project/data/'
        upload_path = os.path.dirname(__file__)

        # Save the file to a predefined filename
        # or use the filename sent by the client:
        # upload_filename = ufile.filename
        upload_filename = 'saved.txt'

        upload_file = os.path.normpath(
            os.path.join(upload_path, upload_filename))
        size = 0
        with open(upload_file, 'wb') as out:
            while True:
                data = ufile.file.read(8192)
                if not data:
                    break
                out.write(data)
                size += len(data)
        out = '''
File received.
Filename: {}
Length: {}
Mime-type: {}
''' .format(ufile.filename, size, ufile.content_type, data)
        return out

if __name__ == '__main__':
    cherrypy.quickstart(App(), '/', config)

webpage.html

<form method="post" action="http://127.0.0.1:8080/upload" enctype="multipart/form-data">
    <input type="file" name="ufile" />
    <input type="submit" />
</form>

cli.py

这个例子需要 Python 请求包,但是文件可以用普通的 Python 发送到服务器。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import requests

url = 'http://127.0.0.1:8080/upload'
files = {'ufile': open('file.txt', 'rb')}

r = requests.post(url, files=files)

print(r)
print(r.text)

upload.txt

Hello! This file was uploaded to CherryPy.

从浏览器上传

  • $ server.py
  • 在 Web 浏览器中打开 webpage.html
  • 从驱动器中选择文件并提交后,它将保存为 saved.txt

从命令行上传

  • 打开一个控制台并运行 $ server.py
  • 打开另一个控制台并运行 $ cli.py
    • 注意:测试文件 upload.txt 应与 cli.py 在同一目录中
  • 文件 upload.txt 应上传并保存为 saved.txt