Nginx搭建文件服务器实现文件上传

Nginx搭建文件服务器实现文件上传

安装Nginx

  1. 官网http://nginx.org/下载对应的nginx包,推荐使用稳定版本

  2. 上传nginx到linux系统

  3. 安装依赖环境

    (1)安装gcc环境

      yum install gcc-c++
    

    (2)安装PCRE库,用于解析正则表达式

     yum install -y pcre pcre-devel
    

    (3)zlib压缩和解压缩依赖,

     yum install -y zlib zlib-devel
    

    (4)SSL 安全的加密的套接字协议层,用于HTTP安全传输,也就是https

     yum install -y openssl openssl-devel
    
  4. 解压,需要注意,解压后得到的是源码,源码需要编译后才能安装

    tar -zxvf nginx-1.16.1.tar.gz
    
  5. 编译之前,先创建nginx临时目录,如果不创建,在启动nginx的过程中会报错

    mkdir /var/temp/nginx -p
    
  6. 在nginx目录,输入如下命令进行配置,目的是为了创建makefile文件

    ./configure \n    --prefix=/usr/local/nginx \n    --pid-path=/var/run/nginx/nginx.pid \n    --lock-path=/var/lock/nginx.lock \n    --error-log-path=/var/log/nginx/error.log \n    --http-log-path=/var/log/nginx/access.log \n    --with-http_gzip_static_module \n    --http-client-body-temp-path=/var/temp/nginx/client \n    --http-proxy-temp-path=/var/temp/nginx/proxy \n    --http-fastcgi-temp-path=/var/temp/nginx/fastcgi \n    --http-uwsgi-temp-path=/var/temp/nginx/uwsgi \n    --http-scgi-temp-path=/var/temp/nginx/scgi
    
    • 配置命令:

      命令解释
      –prefix指定nginx安装目录
      –pid-path指向nginx的pid
      –lock-path锁定安装文件,防止被恶意篡改或误操作
      –error-log错误日志
      –http-log-pathhttp日志
      –with-http_gzip_static_module启用gzip模块,在线实时压缩输出数据流
      –http-client-body-temp-path设定客户端请求的临时目录
      –http-proxy-temp-path设定http代理临时目录
      –http-fastcgi-temp-path设定fastcgi临时目录
      –http-uwsgi-temp-path设定uwsgi临时目录
      –http-scgi-temp-path设定scgi临时目录
  7. make编译

    make
    
  8. 安装

    make install
    
  9. 进入sbin目录启动nginx

    ./nginx
    
    • 停止:./nginx -s stop
    • 重新加载:./nginx -s reload
  10. 修改配置文件

    切换至安装目录

    cd /usr/local/nginx/conf
    

    修改文件

    vim nginx.conf
    

    主要是修改server配置节的内容,配置文件路径

    location ~.* {							#可识别的文件
    	root /usr/local/nginx/image/;  		#图片的映射路径
        autoindex on;  						#开启自动索引
        expires 1h;            				#过期时间
    }
    

    重启nginx

    ./nginx -s reload
    

上传文件功能实现

pom.xml

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

application.yml

# ftp 服务器配置
ftp:
  # 服务器地址
  fileUrl: http://10.10.10.15:80/
  # 服务器ip
  host: 10.10.10.15
  # 服务器登录用户名
  userName: root
  # 服务器密码
  password: Sq6sQJXDyTQo
  # 服务器端口号
  port: 22
  # 文件存储路径
  rootPath: /usr/local/nginx/file

核心工具类

@Component
public class FtpUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    /**
     * ftp服务器ip地址
     */
    private static String host;

    /**
     * 端口
     */
    private static int port;

    /**
     * 用户名
     */
    private static String userName;


    /**
     * 密码
     */
    private static String password;

    /**
     * 存放文件的根目录
     */
    private static String rootPath;

    /**
     * 存放文件的路径
     */
    private static String fileUrl;

    @Value("${ftp.host}")
    public void setHost(String host) {
        FtpUtil.host = host;
    }
    @Value("${ftp.port}")
    public void setPort(int port) {
        FtpUtil.port = port;
    }
    @Value("${ftp.userName}")
    public void setUserName(String userName) {
        FtpUtil.userName = userName;
    }
    @Value("${ftp.password}")
    public void setPassword(String password) {
        FtpUtil.password = password;
    }
    @Value("${ftp.rootPath}")
    public void setRootPath(String rootPath) {
        FtpUtil.rootPath = rootPath;
    }
    @Value("${ftp.fileUrl}")
    public void setFileUrl(String fileUrl) {
        FtpUtil.fileUrl = fileUrl;
    }

    private static ChannelSftp getChannel() throws Exception {
        JSch jsch = new JSch();

        // ->ssh root@host:port
        Session sshSession = jsch.getSession(userName, host, port);
        // 密码
        sshSession.setPassword(password);

        Properties sshConfig = new Properties();
        // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
        sshSession.setConfig("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        //设置登陆超时时间
        // 注意!!这里不设置超时间会报错
        sshSession.connect(60000);

        Channel channel = sshSession.openChannel("sftp");
        channel.connect(1000);

        return (ChannelSftp) channel;
    }

    /**
     * ftp上传文件
     *
     * @param inputStream 文件io流
     * @param imagePath   路径,不存在就创建目录
     * @param imagesName  文件名称
     * @return urlStr 文件的存放路径
     */
    public static String putFile(InputStream inputStream, String fileName, String type) {
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + "/" + type + "/";
            createDir(path, sftp);

            // 上传文件
            sftp.put(inputStream, path + fileName);
            logger.info("上传成功!");
            sftp.quit();
            sftp.exit();

            // 处理返回的路径
            String resultFile;
            resultFile = fileUrl + type + "/" + fileName;

            return resultFile;

        } catch (Exception e) {
            logger.error("上传失败:" + e.getMessage());
        }
        return "";
    }

    /**
     * 创建目录
     */
    private static void createDir(String path, ChannelSftp sftp) throws SftpException {
        String[] folders = path.split("/");
        sftp.cd("/");
        for (String folder : folders) {
            if (folder.length() > 0) {
                try {
                    sftp.cd(folder);
                } catch (SftpException e) {
                    sftp.mkdir(folder);
                    sftp.cd(folder);
                }
            }
        }
    }

    /**
     * 删除文件
     */
    public static void delFile(String fileName,String type) {
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + "/" + type + "/" + fileName;
            sftp.rm(path);
            sftp.quit();
            sftp.exit();
        } catch (Exception e) {
            logger.error(" 删除失败:" + e.getMessage());
        }
    }

}

  • 0
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在 Windows 中搭建一个支持上传和下载文件文件服务器,可以使用 Nginx 和一些插件来实现。以下是步骤: 1. 下载 Nginx for Windows,可以从官网下载:http://nginx.org/en/download.html 2. 解压缩下载的 Nginx 文件到某个目录下,例如 C:\nginx。 3. 在 C:\nginx\conf 目录下创建一个名为 nginx.conf 的文件,并在其中添加以下配置: ``` worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root C:/nginx/html; index index.html index.htm; autoindex on; } location /upload { client_max_body_size 100m; alias C:/nginx/upload/; autoindex on; dav_methods PUT DELETE MKCOL COPY MOVE; dav_access user:rw group:rw all:r; } } } ``` 这个配置文件中定义了一个 http 服务,监听 80 端口,其中 /upload 路径是用来上传文件的,其它路径是用来下载文件的。注意修改 root 和 alias 的路径为你自己的路径。 4. 在 C:\nginx\html 目录下创建一个名为 index.html 的文件,用于测试下载文件是否成功。 5. 在 C:\nginx\upload 目录下创建一个名为 index.html 的文件,用于测试上传文件是否成功。 6. 启动 Nginx,打开命令行窗口,切换到 C:\nginx 目录下,执行命令:nginx.exe。 7. 打开浏览器,访问 http://localhost/,应该可以看到 index.html 页面,用于测试下载文件是否成功。 8. 打开浏览器,访问 http://localhost/upload/,应该可以看到 index.html 页面,用于测试上传文件是否成功。 现在你的文件服务器已经搭建好了,可以用来上传和下载文件了。上传文件时,可以使用 PUT 方法,例如使用 curl 命令上传文件: ``` curl -T file.txt http://localhost/upload/ ``` 下载文件时,可以使用 GET 方法,例如使用浏览器访问 http://localhost/file.txt。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值