第二种方式,我在使用上传图片时可以,其他文件出错,不知原因。
class HomeHandler(BaseHandler): @tornado.web.authenticated def get(self): self.render("admin/home.html",nav=1) @tornado.web.authenticated def post(self): upload_path = os.path.join(os.getcwd(),'template\\file\\home') filesuffix = '.png' filename = "PatternRecognitionAndAnalysis"+filesuffix if 'fileToUpload' in self.request.files.keys(): #判断'fileToUpload'是否在self.request.files中 file_metas = self.request.files['fileToUpload'] for meta in file_metas: filepath = os.path.join(upload_path,filename) with open (filepath,'wb') as up: up.write(meta['body']) BM.update("home",{"img":filename}) self.write(json.dumps({"status":1}))1、如果我们把文件保存在静态文件夹中,我们可以直接返回静态路径:
self.write(json.dumps({"url":"/static/file/other/"+ url}))2、动态下载,在需要的时候才下载, 主要用来控制下载权限:
class DownHandler(tornado.web.RequestHandler): def get(self,fileName): with open("download\\" + fileName, "rb") as f: self.set_header('Content-Type','application/octet-stream') self.write(f.read())验证码图片一般只使用一次,如果保存为图片的话还有考虑增删问题,比较麻烦,如果我们将其保存到字符流在渲染给浏览器就会避免这种问题。
import StringIO class IdentifyCodeHandler(BaseHandler): def get(self): #保存于字符流,打印给浏览器 out=StringIO.StringIO() #先打开StringIO codeimg.save(out, "PNG") #通过图片保存到out字符流中去 self.set_header('Content-Type','image/jpg') #必需要设置头部为image,不然浏览器不知道是图片 self.write(out.getvalue()) #读取StringIO中数据