搭建一個文件服務器的方式有不少,本文介紹筆者曾經用過的兩種:java
在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
使用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