使用nginx_upload_module上传模块来上传文件

aries 发表于 2013-11-01 4531 次浏览 标签 : lnmp

nginx upload module原理

官方文档: http://www.grid.net.ru/nginx/upload.en.html

Nginx upload module通过nginx服务来接受用户上传的文件,自动解析请求体中存储的所有文件上传到upload_store指定的目录下。这些文件信息从原始请求体中分离并根据nginx.conf中的配置重新组装好上传参数,交由upload_pass指定的段处理,从而允许处理任意上传文件。每个上传文件中的file字段值被一系列的upload_set_form_field指令值替换。每个上传文件的内容可以从$upload_tmp_path变量读取,或者可以将文件转移到目的目录下。上传的文件移除可以通过upload_cleanup指令控制。如果请求的方法不是POST,模块将返回405错误(405 Not Allowed),该错误提示可以通过error_page指令处理。

具体的过程如下:

  1. 用户访问能够选择上传文件的页面
  2. 用户提交表单
  3. 浏览器把文件和有关文件的信息作为请求的一部分发送给服务器
  4. 服务器把文件保存到临时存储目录下upload_store
  5. upload_pass指定的处理表单提交的php页面将文件从upload_store拷贝到持久存储位置

1、安装模块

cd /soft
wget http://www.grid.net.ru/nginx/download/nginx_upload_module-2.0.12.tar.gz
tar zxvf nginx_upload_module-2.0.12.tar.gz

进入nginx源码目录

cd /home/soft/lnmp/nginx-1.2.7
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --add-module=/data/downfile/nginx_upload_module-2.2.0
make#新增模块,不用make install
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
cp ./objs/nginx /usr/local/nginx/sbin/nginx

2、修改配置文件,在server中增加一下内容

location /upload {
    upload_pass   /info.php;#上传完成后端接受处理文件
    upload_store /data/uptmp;#上传文件夹
    upload_limit_rate 1024k;# 限制上传速度
    upload_set_form_field "${upload_field_name}_name" $upload_file_name;#文件名称
    upload_set_form_field "${upload_field_name}_content_type" $upload_content_type;#文件类型
    upload_set_form_field "${upload_field_name}_path" $upload_tmp_path;#上传到的路径
    upload_aggregate_form_field "${upload_field_name}_md5" $upload_file_md5;#md5
    upload_aggregate_form_field "${upload_field_name}_size" $upload_file_size;#文件大小
    upload_pass_form_field "^submit$|^description$";
    #如果希望把所有的表单字段都传给后端可以用upload_pass_form_field "^.*$";
}

3、前端代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题文档</title>
</head>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<form name="upload" method="POST" enctype="multipart/form-data" action="/upload"><!--提交到上面的/upload-->
<input type="file" name="file"><br>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>

info.php

<?php
    header("Content-Type:text/html; charset=utf-8");
    print_r($_POST);

上传会返回如下图数据

0条评论

如需评论,请填写表单。
换一个

记住我的信息