让nginx支持文件上传的几种模式

文件上传的几种不同语言和不同方法的总结。


第一种模式 : PHP 语言来处理

这个模式比较简单, 用的人也是最多的, 类似的还有用 .net 来实现, jsp来实现, 都是处理表单。只有语言的差别, 本质没有任何差别。

file.php 文件内容如下 :

<?php
  if ($_FILES["file"]["error"] > 0)
  {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
  }
  else
  {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
    {
      echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
      move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
  }
?>

测试命令 :

curl   -F   "action=file.php"   -F   "file=@xxx.c"   http://192.168.1.162/file.php  

这样就可以把本地文件 xxx.c  通过表单的形式提交到服务器, file.php文件就会处理该表单。


第二种模式: lua 语言来处理

这种模式需要用  ngx_lua 模块的支持, 你可以直接下载  ngx_openresty  的源码安装包, 该项目由春哥负责。

春哥为了处理 文件上传, 还专门写了个lua的  upload.lua 模块。

网址为   https://github.com/agentzh/lua-resty-upload    大家可以下载, 里面只用到 upload.lua 文件即可, 把这个文件放到

/usr/local/openresty/lualib/resty/  这个目录即可(该目录是缺省安装的目录, ./configure  --prefix=/usr  可以改变目录)

下来写一个 savefile.lua 的文件来处理上传上来的文件, 文件内容如下 :

package.path = '/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;'
package.cpath = '/usr/local/lib/lua/5.1/?.so;'

local upload = require "upload"

local chunk_size = 4096
local form = upload:new(chunk_size)
local file
local filelen=0
form:set_timeout(0) -- 1 sec
local filename

function get_filename(res)
    local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')
    if filename then 
        return filename[2]
    end
end

local osfilepath = "/usr/local/openresty/nginx/html/"
local i=0
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
        if res[1] ~= "Content-Type" then
            filename = get_filename(res[2])
            if filename then
                i=i+1
                filepath = osfilepath  .. filename
                file = io.open(filepath,"w+")
                if not file then
                    ngx.say("failed to open file ")
                    return
                end
            else
            end
        end
    elseif typ == "body" then
        if file then
            filelen= filelen + tonumber(string.len(res))    
            file:write(res)
        else
        end
    elseif typ == "part_end" then
        if file then
            file:close()
            file = nil
            ngx.say("file upload success")
        end
    elseif typ == "eof" then
        break
    else
    end
end
if i==0 then
    ngx.say("please upload at least one file!")
    return
end


我把上面这个 savefile.lua 文件放到了  nginx/conf/lua/ 目录中

nginx.conf 配置文件中添加如下的配置 :

        location /uploadfile
        {
           content_by_lua_file 'conf/lua/savefile.lua';
        }


用下面的上传命令进行测试成功

curl   -F   "action=uploadfile"   -F   "file=@abc.zip"   http://127.0.0.1/uploadfile


第三种模式: perl 语言来处理

编译 nginx 的时候 用  --with-http_perl_module 让其支持perl脚本

然后用perl来处理表单, 这种模式我还没做测试, 如果有那位弟兄试验过, 帮我补充一下。


下面的代码为 PERL 提交表单的代码:

use strict;
use warnings;
use WWW::Curl::Easy;
use WWW::Curl::Form;

my $curl = WWW::Curl::Easy->new;
my $form = WWW::Curl::Form->new;

    $form->formaddfile("11game.exe", 'FILE1', "multipart/form-data");
#   $form->formadd("FIELDNAME", "VALUE");
    $curl->setopt(CURLOPT_HTTPPOST, $form);

    $curl->setopt(CURLOPT_HEADER,1);
    $curl->setopt(CURLOPT_URL, 'http://127.0.0.1/uploadfile');

    # A filehandle, reference to a scalar or reference to a typeglob can be used here.
    my $response_body;
    $curl->setopt(CURLOPT_WRITEDATA,$response_body);

    # Starts the actual request
    my $retcode = $curl->perform;

    # Looking at the results...
    if ($retcode == 0) 
    {
        print("Transfer went ok
");
        my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
        # judge result and next action based on $response_code
        print("Received response: 
$response_body
");
    }
    else 
    {
        # Error code, type of error, error message
        print("An error happened: $retcode ".$curl->strerror($retcode)." ".$curl->errbuf."
");
    }


服务器端的代码我不是用perl CGI, 而是嵌入nginx 的 perl脚本, 所以处理表单的代码还没有测试通过,等有时间了在研究一下。



第四种模式:用 http 的dav 模块的 PUT 方法

编译 nginx 的时候 用 --with-http_dav_module 参数让其支持 dav 模式

nginx.conf文件中配置如下 :

        location / {
            client_body_temp_path  /usr/local/openresty/nginx/html/tmp;
            dav_methods  PUT DELETE MKCOL COPY MOVE;
            create_full_put_path   on;
            dav_access             group:rw  all:r;
            root   html;
            #index  index.html index.htm;
        }


用下面的命令进行测试可以成功 :

curl  --request   PUT   --data-binary "@11game.exe"   --header "Content-Type: application/octet-stream"    http://127.0.0.1/game.exe

其中11game.exe为上传的本地文件。


只有第四种是 PUT 方法, 其他的三种都属于  POST 表单的方法。



原文地址:https://www.cnblogs.com/dyllove98/p/3225884.html