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

 

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

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

1、使用nginx搭建

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

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目录下的文件了:json

http://127.0.0.1:8123/fileName浏览器

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

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

add_header Content-disposition "attachment";

注意,在nginx.conf中须要设置用户以及用户组,不然可能对本地目录没有操做权限,能够经过ls -ld命令查看当前用户以及用户组:app

个人有用户名为baidu,用户组为staffurl

2、使用java服务

使用java的controller提供文件下载也很是简单,能够用下面的几行代码搞定:spa

@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进行文件的下载。.net

只传入文件名便可。固然,上面的contentType设置的是zip,若是不肯定文件的格式,可使用

application/octet-stream

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

相关文章
相关标签/搜索