测试上传的代码(@后边是路径): 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()