前端页面,简单代码:
<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;
}
}