讓nginx支持文件上傳的幾種模式

文件上傳的幾種不一樣語言和不一樣方法的總結。php


第一種模式 : PHP 語言來處理html


這個模式比較簡單, 用的人也是最多的, 相似的還有用 .net 來實現, jsp來實現, 都是處理表單。只有語言的差異, 本質沒有任何差異。
nginx

file.php 文件內容以下 :
git

<?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"];
    }
  }
?>

測試命令 :github

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

這樣就能夠把本地文件 xxx.c  經過表單的形式提交到服務器, file.php文件就會處理該表單。app


第二種模式: lua 語言來處理
curl


這種模式須要用  ngx_lua 模塊的支持, 你能夠直接下載  ngx_openresty  的源碼安裝包, 該項目由春哥負責。jsp

春哥爲了處理 文件上傳, 還專門寫了個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\n");
        my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
        # judge result and next action based on $response_code
        print("Received response: \n$response_body\n");
    }
    else 
    {
        # Error code, type of error, error message
        print("An error happened: $retcode ".$curl->strerror($retcode)." ".$curl->errbuf."\n");
    }


服務器端的代碼我不是用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爲上傳的本地文件。


本人打算用perl腳原本PUT二進制文件, 可是嘗試失敗, 下面的代碼能夠PUT文本文件,沒法PUT二進制文件,有那我知道的給我回復一下,不勝感激。

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;

# require HTTP::Request;
 my $r = HTTP::Request->new();
    $r->method("PUT");
    $r->uri("http://127.0.0.1/ssss.txt");
    $r->content("ssssssssssssss");
my $ua = LWP::UserAgent->new;
my $res = $ua->request($r);

#二進制文件假如很大, 也不可能賦值給一個變量啊。 官方資料也沒有找到PUT二進制文件的方法。鬱悶。。。


只有第四種是 PUT 方法, 其餘的三種都屬於  POST 表單的方法。

相關文章
相關標籤/搜索