使用 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