使用nginx搭建文件下载服务器

搭建一个文件服务器的方式有很多,本文介绍笔者曾经用过的两种:

  • 使用nginx
  • 使用java服务,通过controller提供

一、使用nginx搭建

在nginx.conf中直接配置server即可,示例代码如下:

user felice felice;
worker_processes auto;
master_process on;
pid log/nginx.pid;

error_log log/error.log warn;
error_log log/info.log info;

events {
    worker_connections  4096;
}

http {
    server_tokens off;

    client_header_buffer_size 8k;
    client_max_body_size 130m;
    proxy_buffer_size   64k;
    proxy_buffers   8 64k;


    log_format access '$remote_addr $host $remote_user [$time_local] $status $request_length $body_bytes_sent $request_time 0 0 0 - "-" "$request" "$http_referer" "$http_user_agent" $http_cookie $bytes_sent';
    access_log log/access.log access;

    keepalive_requests 16;
    keepalive_timeout  5;

    server {
        listen 8123;
        server_name  localhost;
        charset utf-8;

        location / {
            default_type  'application/octet-stream';
            add_header Content-disposition "attachment";
            root    /User/sonofelice/mm;
         }
     }

}

启动nginx之后,通过请求下面的url就可以下载/User/sonofelice/mm目录下的文件了:

http://127.0.0.1:8123/fileName

在host:port/后面直接跟对应目录下的文件名称即可。

如果强制浏览器下载文件,而不是进行json解析后直接显示内容,需要设置header选项 

add_header Content-disposition "attachment";

注意,在nginx.conf中需要设置用户以及用户组,否则可能对本地目录没有操作权限,可以通过ls -ld命令查看当前用户以及用户组:

我的有用户名为baidu,用户组为staff

二、使用java服务

使用java的controller提供文件下载也非常简单,可以用下面的几行代码搞定:

@RestController
@RequestMapping("/")
@Slf4j
public class FileDownloadController {

    @RequestMapping(method = RequestMethod.GET, value = "/{fileName}")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) {
        Path file = Paths.get(fileName);
        if (Files.exists(file)) {
            response.setContentType("application/zip");
            try {
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                Files.copy(file, response.getOutputStream());
            } catch (IOException e) {
                log.error("File download error:", e);
            }
        }
    }
}

在启动java服务之后,也可以通过第一节中的方式请求url进行文件的下载。

只传入文件名即可。当然,上面的contentType设置的是zip,如果不确定文件的格式,可以使用

application/octet-stream

HTTP Content-type常用对照表参考: http://tool.oschina.net/commons

原文地址:https://www.cnblogs.com/sonofelice/p/8480350.html