python tornado 服务端支持 图片上传,查看

前端页面,简单代码:

            <html>
              <head><title>Upload File</title></head>
              <body>
                <form action='/api/upload' enctype="multipart/form-data" method='post'>
                <input type='file' name='file'/><br/>
                <input type='submit' value='submit'/>
                </form>
              </body>
            </html>

后端代码:


class UploadHandler(BaseHandler):
    @coroutine
    def get(self):
        """接口返回图片"""
        file_path= "xxxx"
        with open(file_path, 'rb') as f:
            self.set_header("Content-Type", "image/jpg")
            self.write(f.read())

    @coroutine
    def post(self, *args, **kwargs):
        size = int(self.request.headers.get('Content-Length'))
        if size / 1000.0 > 2000:
            self.set_status(400)
            self.write({'msg': self._("上传图片不能大于2M.")})
            return
        file_info = self.request.files['file'][0]
        path = "/var/www/demo/static/upload"
        save_path= os.path.join(path, file_info['filename'])               
        app_path = absolute_path[save_path.rindex('upload'):]     
        try:
            with open(save_path, 'wb') as f:
                f.write(file_info['body'])
                self.write(escape.json_encode({
                    'path': app_path
                }))
        except Exception as e:
            app_log.error(e)
            raise HTTPError(500)

上传里面,其实还有好几件事情要做:

(1)限制文件大小: Content-Length

(2)限制文件格式:这个看后缀

(3)是否要压缩图片?

(4)找个专用文件服务器存储?云存储?OSS存储?

如果用上述代码的 GET方法去获取图片,若图片没限制大小,或请求多, 会影响服务器。

最好还是在nginx里配置图片存放访问路径最好。代码只需要在上传成功后,返回图片的地址。

nginx:

         加了下面的upload配置。网页访问:    www.xxx.cn/upload/logo/2018/08/12/xx.jpg ,将会访问到 '/var/www/demo/static' + '/upload/logo/2018/08/12/xx.jpg' ,即/var/www/demo/static/upload/logo/2018/08/12/xx.jpg

server {
     location /upload/ {
            root /var/www/demo/static;
     }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值