Lua Nginx | Openresty: how to get POST data


Case 1: client_body_in_file_only off;

	location /test/post3 {
		default_type 'text/plain';
		client_max_body_size 100m;
         client_body_buffer_size 50k;
		 
		 #lua_need_request_body on;
		 
		content_by_lua_block{
			  ngx.req.read_body() ---- don't require if use: lua_need_request_body on;
			  local args, err = ngx.req.get_uri_args()
			   
			  local request_method = ngx.var.request_method
			   
			  local data = ngx.req.get_body_data()
			   
			  local file = nil
			  local body = {
				  url = ngx.var.uri,
				  query = args,
				  type = request_method,
				  post = data
			  }
			   
			  ngx.say(body.post)
		}
		
	}

Case 2:
client_body_in_file_only clean;
client_body_in_file_only on;

	location /test/post {
		default_type 'text/plain';
		client_max_body_size 100m;
         client_body_buffer_size 50k;
		 client_body_in_file_only clean;
	
		content_by_lua_block{
			  ngx.req.read_body() -- don't require if use: lua_need_request_body on;
			  local args, err = ngx.req.get_uri_args()
			   
			  local request_method = ngx.var.request_method
			   
			  local data  
			   
			  local file = nil
			  local body = {
				  url = ngx.var.uri,
				  query = args,
				  type = request_method,
				  post = data
			  }
			   
			  if request_method == 'POST' or request_method == 'PUT' then
				   
				  local body_file = ngx.req.get_body_file()
					if body_file then
						 
						local body_file_handle, err = io.open(body_file, "r")
						if body_file_handle then
							body_file_handle:seek("set")
							body.post = body_file_handle:read("*a")
							body_file_handle:close()
						else
							body.post = ""
							 
						end
				    else
						body.post = ""
						 
					end
				  file = 1
			  end
			  
			  ngx.say(body.post)
		}
		
	}

We recommend using client_body_in_file_only clean; and read binary file when PUT content of file to upload:

local body_file_handle, err = io.open(body_file, "rb")

Leave a Reply