前言 公司最近有做文件服务器的需求,并且使用到了Nginx做负载均衡服务器,顺水推舟,就想着顺便用作文件服务器算了,实际上它也非常适合。 Nginx是一种轻巧、高效的WEB服务器,用作文件服务器非常合适。但是如果需要一些高级功能,如FTP远
公司最近有做文件服务器的需求,并且使用到了Nginx做负载均衡服务器,顺水推舟,就想着顺便用作文件服务器算了,实际上它也非常适合。
Nginx是一种轻巧、高效的WEB服务器,用作文件服务器非常合适。但是如果需要一些高级功能,如FTP远程访问、多用户管理,可能需要选择更为复杂的方案,例如Apache或FileZilla Server。
sudo apt-get updatesudo apt-get install nginx
sudo systemctl start nginx
sudo nano /etc/nginx/sites-available/myfileserver
server { listen 80; server_name test.com; location / { #指向文件存放的位置 root /path/to/file; autoindex on; autoindex_exact_size off; charset utf-8; }}
这个配置文件表示监听在端口80上的请求,同时指向存储文件的目录并开启文件列表功能
!wq
我们是用Java做的接口,使用SpringBoot框架+Maven
org.springframework.boot spring-boot-starter-web
#服务端口server.port=8080 #指定Nginx文件服务器地址和文件存放位置fileserver.url=test.com fileserver.path=/path/to/file/
@Controllerpublic class FileController { @Value("${fileserver.path}") private String fileServerPath; @PostMapping("/upload") public String uploadFile(Model model, @RequestParam("file") MultipartFile file) { try { Path filePath = Paths.get(fileServerPath + "/" + file.getOriginalFilename()); Files.write(filePath, file.getBytes()); model.addAttribute("message", "File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); model.addAttribute("message", "File upload failed"); } return "uploadFORM"; } @GetMapping("/download/{fileName:.+}") public ResponseEntity downloadFile(@PathVariable("fileName") String fileName{ Path filePath = Paths.get(fileServerPath + "/" + fileName); HttpHeaders headers = new HttpHeaders(); try { byte[] data = Files.readAllBytes(filePath); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", fileName); headers.setContentLength(data.length); return new ResponseEntity(data, headers, httpstatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity(HttpStatus.NOT_FOUND); } } @GetMapping("/") public String getFiles(Model model) { List fileList = new ArrayList<>(); File folder = new File(fileServerPath); File[] files = folder.listFiles(); for(File file : files) { if (file.isFile()) { fileList.add(file.getName()); } } model.addAttribute("fileList", fileList); return "fileList"; }}
至此,文件服务的搭建和文件服务的开发就完成了,能满足基本的文件服务需求
来源地址:https://blog.csdn.net/weixin_42559574/article/details/129943000
--结束END--
本文标题: 详解如何使用Nginx搭建文件服务器及实现文件服务
本文链接: https://www.lsjlt.com/news/399679.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-29
2024-04-29
2024-04-29
2024-04-18
2024-04-17
2024-04-11
2024-04-08
2024-04-08
2024-04-03
2024-03-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0