安装openresty+实现文件上传

yum安装openresty

yum包安装的话很简单

[root@localhost ~]# wget https://openresty.org/package/centos/openresty.repo      #下载yum配置文件
[root@localhost ~]# mv openresty.repo /etc/yum.repos.d/      #移动文件至yum配置目录下
[root@localhost ~]# yum check-update      #检查更新,生效yum配置文件
[root@localhost ~]# yum install -y openresty      #安装
[root@localhost ~]# yum install -y openresty openresty-resty      #安装Openresty和命令行工具 resty
[root@localhost ~]# systemctl start openresty.service       #开启Openresty服务

源码编译安装openresty

其实选择源码包编译安装和yum安装并没有多大区别(对开发实验而言,功能上并没有多大区别),只不过源码包安装可以"个性化"定制:指定安装路径、配置参数,增删模块等
废话不多说,开整
指定安装路径为/web目录(根据自己的需要)
启动HTTP2和真实IP地址转发
编译使用OpenSSL 1.1.1g

[root@localhost ~]# mkdir /web      #创建/web目录
[root@localhost ~]# cd /usr/local/src/      #切换到源码包安装目录
[root@localhost src]# wget https://openresty.org/download/openresty-1.15.8.3.tar.gz      #下载源码包
[root@localhost src]# wget https://www.openssl.org/source/openssl-1.1.1g.tar.gz
[root@localhost src]# tar -zvxf openresty-1.15.8.3.tar.gz       #解压openresty
[root@localhost src]# tar -zvxf openssl-1.1.1g.tar.gz           #解压openssl
[root@localhost src]# cd openresty-1.15.8.3/      #进入安装目录
[root@localhost openresty-1.15.8.3]# ./configure --prefix=/web/openresty --with-http_v2_module --with-http_realip_module --with-openssl=/usr/local/src/openssl-1.1.1g
[root@localhost openresty-1.15.8.3]# gmake 
[root@localhost openresty-1.15.8.3]# gmake install 
验证
[root@localhost ~]# /web/openresty/bin/openresty       #开启openresty服务
[root@localhost ~]# netstat -tunlp|grep 80             #监听80端口
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      70847/nginx: master 
[root@localhost ~]# ps -aux |grep openresty            #查看openresty进程
root      70847  0.0  0.1  33024  1444 ?        Ss   09:10   0:00 nginx: master process /web/openresty/bin/openresty
root      70860  0.0  0.0 112824   976 pts/1    R+   09:10   0:00 grep --color=auto openresty

服务端:使用openresty的lua-resty-upload模块来实现文件上传

接受前端的上传请求,将处理好的文件保存起来

nginx配置

注意:

  1. 文件存储路径
  2. 指定上传逻辑代码路径

在nginx上添加一个server

#cat nginx.conf
user root;
worker_processes  20;

error_log  logs/error.log notice;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    sendfile        on;
    tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    server {
        listen       19999;
        server_name  localhost;
        # 最大允许上传的文件大小
        client_max_body_size 200m;

        location / {
            root   html;
            index  index.html index.htm;
        }
        set $store_dir "/var/ftp/pub/"; # 文件存储路径
        # 文件上传接口:http://xxx:19999/upfile
        location /upfile {
            content_by_lua_file conf/lua/upload.lua; # 实现文件上传的逻辑
        }
        # 文件下载入口: http://xxx:19999/download
        location /download {
            autoindex on;
            autoindex_localtime on;
            root   html;
            index  index.html;
        }
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

实现上传逻辑代码 conf/lua/upload.lua

注意:我使用的是openresty,可以直接引用resty.upload等lua库,如果你是nginx,还需要找到upload.lua、cjson库

#cat /usr/local/openresty/nginx/conf/lua/upload.lua
-- upload.lua
--==========================================
-- 文件上传
--==========================================
local upload = require "resty.upload"
local cjson = require "cjson"
local chunk_size = 4096
local form, err = upload:new(chunk_size)
if not form then
    ngx.log(ngx.ERR, "failed to new upload: ", err)
    ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
end
form:set_timeout(1000)
-- 字符串 split 分割
string.split = function(s, p)
    local rt= {}
    string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
    return rt
end
-- 支持字符串前后 trim
string.trim = function(s)
    return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-- 文件保存的根路径
local saveRootPath = ngx.var.store_dir
-- 保存的文件对象
local fileToSave
--文件是否成功保存
local ret_save = false
while true do
    local typ, res, err = form:read()
    if not typ then
        ngx.say("failed to read: ", err)
        return
    end
    if typ == "header" then
        -- 开始读取 http header
        -- 解析出本次上传的文件名
        local key = res[1]
        local value = res[2]
        if key == "Content-Disposition" then
            -- 解析出本次上传的文件名
            -- form-data; name="testFileName"; filename="testfile.txt"
            local kvlist = string.split(value, ';')
            for _, kv in ipairs(kvlist) do
                local seg = string.trim(kv)
                if seg:find("filename") then
                    local kvfile = string.split(seg, "=")
                    local filename = string.sub(kvfile[2], 2, -2)
                    if filename then
                        fileToSave = io.open(saveRootPath .. filename, "w+")
                        if not fileToSave then
                            ngx.say("failed to open file ", filename)
                            return
                        end
                        break
                    end
                end
            end
        end
    elseif typ == "body" then
        -- 开始读取 http body
        if fileToSave then
            fileToSave:write(res)
        end
    elseif typ == "part_end" then
        -- 文件写结束,关闭文件
        if fileToSave then
            fileToSave:close()
            fileToSave = nil
        end

        ret_save = true
    elseif typ == "eof" then
        -- 文件读取结束
        break
    else
        ngx.log(ngx.INFO, "do other things")
    end
end
if ret_save then
    ngx.say("save file ok")
end


版权声明:本文为ethnicitybeta原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。