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

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

  21244人阅读  评论(2)  收藏  举报

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


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

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

file.php 文件内容如下 :

[php]  view plain  copy
  1. <?php  
  2.   if ($_FILES["file"]["error"] > 0)  
  3.   {  
  4.     echo "Return Code: " . $_FILES["file"]["error"] . "<br />";  
  5.   }  
  6.   else  
  7.   {  
  8.     echo "Upload: " . $_FILES["file"]["name"] . "<br />";  
  9.     echo "Type: " . $_FILES["file"]["type"] . "<br />";  
  10.     echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";  
  11.     echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";  
  12.   
  13.     if (file_exists("upload/" . $_FILES["file"]["name"]))  
  14.     {  
  15.       echo $_FILES["file"]["name"] . " already exists. ";  
  16.     }  
  17.     else  
  18.     {  
  19.       move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);  
  20.       echo "Stored in: " . "upload/" . $_FILES["file"]["name"];  
  21.     }  
  22.   }  
  23. ?>  

测试命令 :

curl   -F   "action=file.php"   -F   "[email protected]"   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 的文件来处理上传上来的文件, 文件内容如下 :

[plain]  view plain  copy
  1. package.path = '/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;'  
  2. package.cpath = '/usr/local/lib/lua/5.1/?.so;'  
  3.   
  4. local upload = require "upload"  
  5.   
  6. local chunk_size = 4096  
  7. local form = upload:new(chunk_size)  
  8. local file  
  9. local filelen=0  
  10. form:set_timeout(0) -- 1 sec  
  11. local filename  
  12.   
  13. function get_filename(res)  
  14.     local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')  
  15.     if filename then   
  16.         return filename[2]  
  17.     end  
  18. end  
  19.   
  20. local osfilepath = "/usr/local/openresty/nginx/html/"  
  21. local i=0  
  22. while true do  
  23.     local typ, res, err = form:read()  
  24.     if not typ then  
  25.         ngx.say("failed to read: ", err)  
  26.         return  
  27.     end  
  28.     if typ == "header" then  
  29.         if res[1] ~= "Content-Type" then  
  30.             filename = get_filename(res[2])  
  31.             if filename then  
  32.                 i=i+1  
  33.                 filepath = osfilepath  .. filename  
  34.                 file = io.open(filepath,"w+")  
  35.                 if not file then  
  36.                     ngx.say("failed to open file ")  
  37.                     return  
  38.                 end  
  39.             else  
  40.             end  
  41.         end  
  42.     elseif typ == "body" then  
  43.         if file then  
  44.             filelen= filelen + tonumber(string.len(res))      
  45.             file:write(res)  
  46.         else  
  47.         end  
  48.     elseif typ == "part_end" then  
  49.         if file then  
  50.             file:close()  
  51.             file = nil  
  52.             ngx.say("file upload success")  
  53.         end  
  54.     elseif typ == "eof" then  
  55.         break  
  56.     else  
  57.     end  
  58. end  
  59. if i==0 then  
  60.     ngx.say("please upload at least one file!")  
  61.     return  
  62. end  

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

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

[html]  view plain  copy
  1. location /uploadfile  
  2. {  
  3.    content_by_lua_file 'conf/lua/savefile.lua';  
  4. }  

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

curl   -F   "action=uploadfile"   -F   "[email protected]"   http://127.0.0.1/uploadfile


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

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

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


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

[plain]  view plain  copy
  1. use strict;  
  2. use warnings;  
  3. use WWW::Curl::Easy;  
  4. use WWW::Curl::Form;  
  5.   
  6. my $curl = WWW::Curl::Easy->new;  
  7. my $form = WWW::Curl::Form->new;  
  8.   
  9.     $form->formaddfile("11game.exe", 'FILE1', "multipart/form-data");  
  10. #   $form->formadd("FIELDNAME", "VALUE");  
  11.     $curl->setopt(CURLOPT_HTTPPOST, $form);  
  12.   
  13.     $curl->setopt(CURLOPT_HEADER,1);  
  14.     $curl->setopt(CURLOPT_URL, 'http://127.0.0.1/uploadfile');  
  15.   
  16.     # A filehandle, reference to a scalar or reference to a typeglob can be used here.  
  17.     my $response_body;  
  18.     $curl->setopt(CURLOPT_WRITEDATA,\$response_body);  
  19.   
  20.     # Starts the actual request  
  21.     my $retcode = $curl->perform;  
  22.   
  23.     # Looking at the results...  
  24.     if ($retcode == 0)   
  25.     {  
  26.         print("Transfer went ok\n");  
  27.         my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);  
  28.         # judge result and next action based on $response_code  
  29.         print("Received response: \n$response_body\n");  
  30.     }  
  31.     else   
  32.     {  
  33.         # Error code, type of error, error message  
  34.         print("An error happened: $retcode ".$curl->strerror($retcode)." ".$curl->errbuf."\n");  
  35.     }  

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



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

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

nginx.conf文件中配置如下 :

[plain]  view plain  copy
  1. location / {  
  2.     client_body_temp_path  /usr/local/openresty/nginx/html/tmp;  
  3.     dav_methods  PUT DELETE MKCOL COPY MOVE;  
  4.     create_full_put_path   on;  
  5.     dav_access             group:rw  all:r;  
  6.     root   html;  
  7.     #index  index.html index.htm;  
  8. }  

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

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二进制文件,有那我知道的给我回复一下,不胜感激。

[plain]  view plain  copy
  1. use strict;  
  2. use warnings;  
  3.   
  4. use LWP::UserAgent;  
  5. use HTTP::Request;  
  6.   
  7. # require HTTP::Request;  
  8.  my $r = HTTP::Request->new();  
  9.     $r->method("PUT");  
  10.     $r->uri("http://127.0.0.1/ssss.txt");  
  11.     $r->content("ssssssssssssss");  
  12. my $ua = LWP::UserAgent->new;  
  13. my $res = $ua->request($r);  
  14.   
  15. #二进制文件假如很大, 也不可能赋值给一个变量啊。 官方资料也没有找到PUT二进制文件的方法。郁闷。。。  


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

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


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

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

file.php 文件内容如下 :

[php]  view plain  copy
  1. <?php  
  2.   if ($_FILES["file"]["error"] > 0)  
  3.   {  
  4.     echo "Return Code: " . $_FILES["file"]["error"] . "<br />";  
  5.   }  
  6.   else  
  7.   {  
  8.     echo "Upload: " . $_FILES["file"]["name"] . "<br />";  
  9.     echo "Type: " . $_FILES["file"]["type"] . "<br />";  
  10.     echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";  
  11.     echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";  
  12.   
  13.     if (file_exists("upload/" . $_FILES["file"]["name"]))  
  14.     {  
  15.       echo $_FILES["file"]["name"] . " already exists. ";  
  16.     }  
  17.     else  
  18.     {  
  19.       move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);  
  20.       echo "Stored in: " . "upload/" . $_FILES["file"]["name"];  
  21.     }  
  22.   }  
  23. ?>  

测试命令 :

curl   -F   "action=file.php"   -F   "[email protected]"   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 的文件来处理上传上来的文件, 文件内容如下 :

[plain]  view plain  copy
  1. package.path = '/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;'  
  2. package.cpath = '/usr/local/lib/lua/5.1/?.so;'  
  3.   
  4. local upload = require "upload"  
  5.   
  6. local chunk_size = 4096  
  7. local form = upload:new(chunk_size)  
  8. local file  
  9. local filelen=0  
  10. form:set_timeout(0) -- 1 sec  
  11. local filename  
  12.   
  13. function get_filename(res)  
  14.     local filename = ngx.re.match(res,'(.+)filename="(.+)"(.*)')  
  15.     if filename then   
  16.         return filename[2]  
  17.     end  
  18. end  
  19.   
  20. local osfilepath = "/usr/local/openresty/nginx/html/"  
  21. local i=0  
  22. while true do  
  23.     local typ, res, err = form:read()  
  24.     if not typ then  
  25.         ngx.say("failed to read: ", err)  
  26.         return  
  27.     end  
  28.     if typ == "header" then  
  29.         if res[1] ~= "Content-Type" then  
  30.             filename = get_filename(res[2])  
  31.             if filename then  
  32.                 i=i+1  
  33.                 filepath = osfilepath  .. filename  
  34.                 file = io.open(filepath,"w+")  
  35.                 if not file then  
  36.                     ngx.say("failed to open file ")  
  37.                     return  
  38.                 end  
  39.             else  
  40.             end  
  41.         end  
  42.     elseif typ == "body" then  
  43.         if file then  
  44.             filelen= filelen + tonumber(string.len(res))      
  45.             file:write(res)  
  46.         else  
  47.         end  
  48.     elseif typ == "part_end" then  
  49.         if file then  
  50.             file:close()  
  51.             file = nil  
  52.             ngx.say("file upload success")  
  53.         end  
  54.     elseif typ == "eof" then  
  55.         break  
  56.     else  
  57.     end  
  58. end  
  59. if i==0 then  
  60.     ngx.say("please upload at least one file!")  
  61.     return  
  62. end  

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

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

[html]  view plain  copy
  1. location /uploadfile  
  2. {  
  3.    content_by_lua_file 'conf/lua/savefile.lua';  
  4. }  

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

curl   -F   "action=uploadfile"   -F   "[email protected]"   http://127.0.0.1/uploadfile


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

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

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


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

[plain]  view plain  copy
  1. use strict;  
  2. use warnings;  
  3. use WWW::Curl::Easy;  
  4. use WWW::Curl::Form;  
  5.   
  6. my $curl = WWW::Curl::Easy->new;  
  7. my $form = WWW::Curl::Form->new;  
  8.   
  9.     $form->formaddfile("11game.exe", 'FILE1', "multipart/form-data");  
  10. #   $form->formadd("FIELDNAME", "VALUE");  
  11.     $curl->setopt(CURLOPT_HTTPPOST, $form);  
  12.   
  13.     $curl->setopt(CURLOPT_HEADER,1);  
  14.     $curl->setopt(CURLOPT_URL, 'http://127.0.0.1/uploadfile');  
  15.   
  16.     # A filehandle, reference to a scalar or reference to a typeglob can be used here.  
  17.     my $response_body;  
  18.     $curl->setopt(CURLOPT_WRITEDATA,\$response_body);  
  19.   
  20.     # Starts the actual request  
  21.     my $retcode = $curl->perform;  
  22.   
  23.     # Looking at the results...  
  24.     if ($retcode == 0)   
  25.     {  
  26.         print("Transfer went ok\n");  
  27.         my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);  
  28.         # judge result and next action based on $response_code  
  29.         print("Received response: \n$response_body\n");  
  30.     }  
  31.     else   
  32.     {  
  33.         # Error code, type of error, error message  
  34.         print("An error happened: $retcode ".$curl->strerror($retcode)." ".$curl->errbuf."\n");  
  35.     }  

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



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

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

nginx.conf文件中配置如下 :

[plain]  view plain  copy
  1. location / {  
  2.     client_body_temp_path  /usr/local/openresty/nginx/html/tmp;  
  3.     dav_methods  PUT DELETE MKCOL COPY MOVE;  
  4.     create_full_put_path   on;  
  5.     dav_access             group:rw  all:r;  
  6.     root   html;  
  7.     #index  index.html index.htm;  
  8. }  

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

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二进制文件,有那我知道的给我回复一下,不胜感激。

[plain]  view plain  copy
  1. use strict;  
  2. use warnings;  
  3.   
  4. use LWP::UserAgent;  
  5. use HTTP::Request;  
  6.   
  7. # require HTTP::Request;  
  8.  my $r = HTTP::Request->new();  
  9.     $r->method("PUT");  
  10.     $r->uri("http://127.0.0.1/ssss.txt");  
  11.     $r->content("ssssssssssssss");  
  12. my $ua = LWP::UserAgent->new;  
  13. my $res = $ua->request($r);  
  14.   
  15. #二进制文件假如很大, 也不可能赋值给一个变量啊。 官方资料也没有找到PUT二进制文件的方法。郁闷。。。  


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

猜你喜欢

转载自blog.csdn.net/caofengtao1314/article/details/52837948