python tornado 下载和上传文件

测试上传的代码(@后边是路径):
curl -F "key=value" -F "filename=@/tmp/static/t.png" http://localhost:8888/upload

如果使用了-F参数,curl会以multipart/form-data的方式发送POST请求。-F以key=value的形式指定要上传的参数,如果是文件,则需要使用key=@file的形式。

如果使用-d命令,curl会以application/x-www-url-encoded格式上传参数。

curl -d "action=del" -d "id=12" http://localhost/test
  •  

如果要以json格式上传参数,需要使用-H在命令中指定。

curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost/api/login

 

# 这里是代码

def uuid_naming_strategy(original_name):
    "File naming strategy that ignores original name and returns an UUID"
    return str(uuid.uuid4())


class UploadHandler(tornado.web.RequestHandler):
    "Handle file uploads."

    def initialize(self, upload_path, naming_strategy):
        """Initialize with given upload path and naming strategy.

        :keyword upload_path: The upload path.
        :type upload_path: str
        :keyword naming_strategy: File naming strategy.
        :type naming_strategy: (str) -> str function

        """
        self.upload_path = upload_path
        if naming_strategy is None:
            naming_strategy = uuid_naming_strategy
        self.naming_strategy = naming_strategy

    def post(self):
        fileinfo = self.request.files['filename'][0]
        filename = fileinfo['filename'] #self.naming_strategy(fileinfo['filename'])
        try:
            with open(os.path.join(self.upload_path, filename), 'w') as fh:
                fh.write(fileinfo['body'])
            logging.info("%s uploaded %s, saved as %s",
                         str(self.request.remote_ip),
                         str(fileinfo['filename']),
                         filename)
        except IOError as e:
            logging.error("Failed to write file due to IOError %s", str(e))

 

后边的参数可以设置basepath 是什么,网上的回答,大部分没有这一步。

application = tornado.web.Application([
    (r'/ws', WSHandler),
    (r'/static/(.*)', DownloadHandler, dict(basepath="/tmp/static/") ),
    (r"/upload", UploadHandler,
     dict(upload_path="/tmp", naming_strategy=None)),
])
class DownloadHandler(tornado.web.RequestHandler):
    def initialize(self, basepath):
        self.database = basepath

    def get(self,filename):
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename=%s' % filename)

        path = os.path.join(self.basepath,filename)
        with open( path, 'rb') as f:
            while True:
                data = f.read(4096)
                if not data:
                    break
                self.write(data)

        self.finish()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值