Nginx-module-文件上传模块的安装及使用

本文详细介绍了如何在Nginx中安装和使用文件上传模块,包括下载不同组件,解决编译问题,配置文件上传模块,以及处理后端代码与中文文件名的解码问题。

Nginx-module-文件上传模块的安装及使用

1. 安装

下面指令的执行的工作目录:/usr/local/software/

下载和安装的nginx及 ngx_cache_purge插件

1.1下载nginx

#下载
wget http://nginx.org/download/nginx-1.18.0.tar.gz
​
tar -zxvf nginx-1.18.0.tar

1.2 下载 ngx_cache_purge插件

  #下载ngx_cache_purge 插件
  git clone https://github.com/FRiCKLE/ngx_cache_purge.git
  #加压缩 
  tar -zxvf ngx_cache_purge/

1.3下载 upload module

开始我下载pload module的版本2.2.0,在执行编译make && make install的过程中, 引用md5.h 文件找不到, 最后我升级到最新的版本2.3.0。

下载地址:https://codeload.github.com/vkholodkov/nginx-upload-module/tar.gz/refs/tags/2.3.0

原作者好久都没有对代码进行维护, 在git hub发现,另一位作者对文件上传模块进行修改,不会出现 md5.h 找不到的问题,https://github.com/winshining/nginx-upload-module , 可以从这个站点下载源码进行编译。

1.4 执行configure指令进行

执行configure指令进行依赖检查和生产Makefile

./configure --prefix=/usr/local/nginx1.18 \
--with-pcre --with-http_ssl_module \
--addmodule=../ngx_cache_purge  

关于configure指令的使用,请参考文章configure

1.5 编译和安装

sudo make && make install

1.6 安装 文件上传模块

./configure --add-module=../nginx-upload-module-2.3.0 && make && make install

大家可能有疑惑为什么文件上传组件不和nginx一起安装, 因为以前安装的时候,./configure失败, 具体错误消息"error no nginx-upload-module-2.3.0/config found ", 我到源码路径下查看,发现是存在的。 之后分两步来安装,就成功了。

大家在安装的过程中,可能遇到编译的过程中有警告,导致编译失败, 我是把nginx目录, objs/Makefile里 -Werror 参数给去掉,然后执行make && make install

2. 文件上传模块的配置

user  root;
worker_processes  1;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
 
events {
    worker_connections  1024;
}
 
 
http {
    include       mime.types;
    default_type  application/octet-stream;
​
    charset utf-8; 
 
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
 
    #gzip  on;
  
    #后端处理上传文件的的location
    upstream application1 {
        server 127.0.0.1:8080;
    }
 
    server {
        listen       80;
        client_max_body_size 100m;
        location / {
           proxy_pass http://application1;
           proxy_set_header Host $host;
           proxy_set_header X-Real-Ip $remote_addr;
           proxy_set_header X-Forwarded-For $remote_addr;
       client_max_body_size 100m;
        }
    
    error_page 405 =200 @405;
    
    
        # Upload form should be submitted to this location
        location /attachment {
 
        if ($request_method = 'GET'){
            root html;
        }
        if ($request_method = 'POST'){
            
            # Pass altered request body to this location
            upload_pass @test;
 
            upload_resumable 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 /usr/local/software/nginx/upload_dir;
​
            #upload_state_store /usr/local/software/nginx/upload_state;
             
            # Allow uploaded files to be read only by user
            upload_store_access user:rw;
 
            # 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_args on; 
​
            upload_pass_form_field "^.*$";
            upload_cleanup 400 404 499 500-505;
          }
        } 
      
        # Pass altered request body to a backend
        location @test {
            proxy_pass http://localhost:8080;
            #return 200;
        }
    }
}

具体每个指令接收和使用说明可以参考:https://github.com/vkholodkov/nginx-upload-module

处理文件文件的后端代码

基于spring boot搭建的web 应用程序。

有一点我要说一下,当上传的文件的名字是中文或者非ascii的时候, nignx的file upload module的传过来的文件名字是乱码, 如上传件 .pdf, 以编码过html entity,需要使用Spring web里一个工具类org.springframework.web.util.HtmlUtils来解码。

​
package com.example.fileupload;
​
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;
​
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Enumeration;
​
@RestController
@Slf4j
public class FileUploadController {
    private static final String PARAM_FILE_NAME = "file1_name";
    private static final String PARAM_FILE_PATH = "file1_path";
    private static final String PARAM_FILE_CONTENT_TYPE = "file1_content_type";
    private static final String PARAM_FILE_SIZE = "file1_size";
​
    @PostMapping("/attachment")
    public String saveCompanyPolicyFulfillAttachment(HttpServletRequest request) {
        System.out.println("start to upload file .....");
        String url;
        try {
            System.out.println("start print out request body info:  ======================");
            request.getParameterMap().forEach(
                    (key, value)-> System.out.println(key +  "- " + Arrays.toString(value)));
            System.out.println("end print out request body info =========================== ");
​
            String fileName =  HtmlUtils.htmlUnescape(request.getParameter(PARAM_FILE_NAME));
            if (StringUtils.hasText(fileName)) {
                String fromFilePath  = request.getParameter(PARAM_FILE_PATH);
                File fromFile = new File(fromFilePath);
                FileCopyUtils.copy(fromFile, new File("/data/upload/", fileName));
​
                if (fromFile.delete()) {
                    System.out.println("successfully delete  " + fromFilePath );
                } else {
                    System.out.println("fail delete  " + fromFilePath );
                }
            }
            return "success";
        } catch (Exception e) {
            log.error(e.toString(), e);
            return "error";
        }
    }
}

参考文档:

nginx文件上传模块 nginx_upload_module_Gฅ的博客-CSDN博客

https://github.com/vkholodkov/nginx-upload-module

https://github.com/winshining/nginx-upload-module

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值