使用 nginx upload 模块和 nginx lua 模块一起实现文件上传

我正在使用 nginx upload 模块将文件上传到服务器。但是,我希望 nginx 将文件上传到不同的路径,而不是上传到 upload_store 中指定的路径。 因此,我借助 nginx-lua 模块在每个请求中更改 upload_store 的值,如下所示。

location /umtest {
            upload_pass /nginx_response;
            set $upload_store '';
            rewrite_by_lua '
                local header = ngx.req.raw_header()
                ngx.say("type header",header)
                dst_path_dir = ngx.req.get_headers()["Dst-Dir"]
                ngx.say("dst_path_dir",dst_path_dir)
                ngx.var.upload_store = dst_path_dir
                ngx.say("upload store path" ,ngx.var.upload_store)
             ';
                upload_set_form_field $upload_field_name.name
               "$upload_file_name";
                upload_set_form_field $upload_field_name.content_type
                "$upload_content_type";
                upload_set_form_field $upload_field_name.path
                "$upload_tmp_path"
                upload_cleanup 400 404 499 500-505;
               }

现在,当我 POST 到 '/umtest' 时,它会更改 upload_store 的值,但不会执行 nginx upload 指令(即,上传不会发生)。当我注释掉 rewrite_by_lua 指令时,上传就会发生。 我的问题是,我们不能同时使用这两个模块来实现这个目的吗?

点赞
用户4984564
用户4984564

既然你已经在使用 Lua,一个显而易见的解决办法就是使用 Lua 读取请求体并将其保存为文件:

-- handle_download.lua
ngx.req.read_body()
local body = ngx.req.get_body_data()
local file = io.open("some_file", 'wb')
file:write(body)
file:close()
location /umtest {
   content_by_lua_file 'handle_download.lua';
}

这只是将整个请求体转储到一个文件中。如果要上传的文件作为 HTML 表单的一部分发送,则也可以使用 ngx.req.get_post_args(),或者甚至可以使用 ngx.req.socket() 自己读取数据作为流(对于非常大的文件很有用)。

2020-02-05 13:43:43