讓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\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為上傳的本地文件。


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



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM