使用nginx-upload-module搭建文件上传服务器

1. nginx文件版本及系统环境

nginx1.17.3
nginx-upload-module2.3.0
系统centos7

2. 文件下载

nginx和nginx-upload-module

1)原生的nginx没有upload-module,需要重新编译nginx,添加nginx-upload-module

2) nginx下载 http://nginx.org/en/download.html,下载最新版

3)nginx-upload-module下载 https://github.com/fdintino/nginx-upload-module/releases,下载最新版

3. 编译

1)将nginx和nginx-upload-module放在解压到/home的目录下

2)在nginx目录下,运行nginx的配置脚本

./configure --prefix=/home/software/nginx --sbin-path=/home/software/nginx/sbin/nginx --conf-path=/home/software/nginx/conf/nginx.conf --with-http_ssl_module --with-http_stub_status_module --add-module=./nginx-upload-module-2.3.0

3)在nginx目录下,安装 make & make install, 完成nginx带上传模块的安装。本次安装时采用了绝对路径,如果需要相对路径自行修改--sbin-path和--conf-path即可。

4. nginx upload配置

server {
        client_max_body_size 100m;
        listen       8077; 
            # Upload form should be submitted to this location
        location /file/ {  
            # Pass altered request body to this location
            upload_pass @fileserver_backend;
            upload_pass_args on;
            # Store files to this directory
            # The directory is hashed, subdirectories 0 1 2 3 4 5 6 7 8 9 should exist
            upload_store /home/software/nginx/tmp-file 1; 
            # Allow uploaded files to be read only by user
            upload_store_access user:rw group:rw all:r;
            # Set specified fields in request body
            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";
       
            # Inform backend about hash and size of a file
            upload_aggregate_form_field "$upload_field_name.md5" "$upload_file_md5";
            upload_aggregate_form_field "$upload_field_name.size" "$upload_file_size";
            upload_pass_form_field "^.*";                                                     
            upload_limit_rate 0;
            upload_cleanup 400-599;
        }
        # Pass altered request body to a backend
        location @fileserver_backend {
             proxy_pass http://127.0.0.1:2230; 
        }
    }   

nginx upload上传的文件会以临时文件的方式存在路劲(/home/software/nginx/tmp-file)中,文件名是文件上传的顺序编号,不带文件后缀。其中关于文件的信息会作为参数传到 fileserver_backend 后续处理程序中,后续程序可以使用多种方式实现,本文提供一种java接口的方式。

5. nginx后续处理程序接口

 @RequestMapping(value = "/file/", method = RequestMethod.POST)
    public ResponseEntity fileRenameAndSave(HttpServletRequest request){
        /**
         * 略
         */
        return ResponseEntity.status(HttpStatus.OK).body("");
    }

至此,nginx linux版上传模块的功能介绍完。nginx windows版上传模块编译包可在 https://download.csdn.net/download/Lpig900911/12287434 下载。