SpringBoot怎麼使用FTP操作文件
簡介
使用 SpringBoot 設定 FTP 伺服器,上傳、刪除、下載檔案。
設定FTP
檢查是否安裝vsftpd
rpm -qa | grep vsftpd
檢修是否已安裝vsftpd 及查看版本號碼.
#安裝vsftpd
yum -y install vsftpd
如果報錯,則使用管理員權限執行
sudo yum -y install vsftpd
#關閉匿名存取
關閉匿名存取後,想存取裡面的檔案就需要帳號和密碼;如果不關,就可以直接存取。
vim /etc/vsftpd/vsftpd.conf
如果提示是唯讀文件,那麼你只需要輸入指令:
sudo vim /etc/vsftpd/vsftpd.conf
如下:
# Example config file /etc/vsftpd/vsftpd.conf # # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daemon more usable. # Please see vsftpd.conf.5 for all compiled in defaults. # # READ THIS: This example file is NOT an exhaustive list of vsftpd options. # Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's # capabilities. # # Allow anonymous FTP? (Beware - allowed by default if you comment this out). anonymous_enable=NO # # Uncomment this to allow local users to log in. local_enable=YES # # Uncomment this to enable any form of FTP write command. write_enable=YES # # Default umask for local users is 077. You may wish to change this to 022, # if your users expect that (022 is used by most other ftpd's) local_umask=022 # # Uncomment this to allow the anonymous FTP user to upload files. This only # has an effect if the above global write enable is activated. Also, you will # obviously need to create a directory writable by the FTP user. # When SELinux is enforcing check for SE bool allow_ftpd_anon_write, allow_ftpd_full_access #anon_upload_enable=YES # # Uncomment this if you want the anonymous FTP user to be able to create # new directories. #anon_mkdir_write_enable=YES # # Activate directory messages - messages given to remote users when they # go into a certain directory. dirmessage_enable=YES # # Activate logging of uploads/downloads. xferlog_enable=YES # # Make sure PORT transfer connections originate from port 20 (ftp-data). connect_from_port_20=YES # # If you want, you can arrange for uploaded anonymous files to be owned by # a different user. Note! Using "root" for uploaded files is not # recommended! #chown_uploads=YES #chown_username=whoever # # You may override where the log file goes if you like. The default is shown # below. #xferlog_file=/var/log/xferlog # # If you want, you can have your log file in standard ftpd xferlog format. # Note that the default log file location is /var/log/xferlog in this case. xferlog_std_format=YES # # You may change the default value for timing out an idle session. #idle_session_timeout=600
關閉匿名存取就是將:anonymous_enable=NO
#啟動服務
systemctl start vsftpd.service
檢視服務狀態
systemctl status vsftpd.service
[root@hadoop-master ~]# systemctl status vsftpd.service ● vsftpd.service - Vsftpd ftp daemon Loaded: loaded (/usr/lib/systemd/system/vsftpd.service; disabled; vendor preset: disabled) Active: active (running) since 一 2022-12-19 10:15:39 CST; 58min ago Process: 21702 ExecStart=/usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf (code=exited, status=0/SUCCESS) Main PID: 21703 (vsftpd) CGroup: /system.slice/vsftpd.service └─21703 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf 12月 19 10:15:39 hadoop-master systemd[1]: Starting Vsftpd ftp daemon... 12月 19 10:15:39 hadoop-master systemd[1]: Started Vsftpd ftp daemon. [root@hadoop-master ~]#
看到綠色的
active(running)
,代表啟動成功正在運作中。
新增 FTP 使用者
因為在 Linux 上,root 使用者是無法登陸 FTP 的。如果你輸入的是 root 用戶,登陸會失敗的。
adduser ftpadmin
設定密碼:
passwd ftpadmin
輸入兩次密碼就 ok 了。
設定允許root使用者登入
將/etc/vsftpd/user_list
檔案和/etc/vsftpd/ftpusers
檔案中的root
這一行註解掉
修改/etc/vsftpd/vsftpd.conf
,在最後一行新增local_root=/
service vsftpd restart
這樣遠端就可以root使用者身分登入ftp了。
檔案儲存位址授權
如儲存位址為:app/upload/
,設定權限為:
chmod 777 /app/upload/
SpringBoot編碼
新增依賴
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
操作檔工具類別
package com.demo.utils; import com.jcraft.jsch.*; import com.demo.dto.UploadFileDto; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.FileOutputStream; import java.util.Properties; /** * @ClassName: UploadFileUtils.java * @Description: 上传文件 * @Author: tanyp * @Date: 2022/12/19 10:38 **/ @Slf4j public class UploadFileUtils { /** * @MonthName: upload * @Description: 上传文件 * @Author: tanyp * @Date: 2022/12/19 10:38 * @Param: [dto] * @return: boolean **/ public static boolean upload(UploadFileDto dto) throws Exception { log.info("============上传文件开始=============="); Boolean result = false; ChannelSftp sftp = null; Channel channel = null; Session sshSession = null; try { JSch jSch = new JSch(); jSch.getSession(dto.getAccount(), dto.getHost(), dto.getPort()); sshSession = jSch.getSession(dto.getAccount(), dto.getHost(), dto.getPort()); sshSession.setPassword(dto.getPasswd()); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; sftp.cd(dto.getWorkingDir()); sftp.put(dto.getInputStream(), dto.getFileName()); result = true; log.info("============上传文件结束=============="); } catch (JSchException e) { result = false; log.error("=====上传文件异常:{}", e.getMessage()); e.printStackTrace(); } finally { closeChannel(sftp); closeChannel(channel); closeSession(sshSession); } return result; } /** * @MonthName: delete * @Description: 删除文件 * @Author: tanyp * @Date: 2022/12/19 10:38 * @Param: [dto] * @return: boolean **/ public static boolean delete(UploadFileDto dto) throws Exception { log.info("============删除文件开始=============="); Boolean result = false; ChannelSftp sftp = null; Channel channel = null; Session sshSession = null; try { JSch jSch = new JSch(); jSch.getSession(dto.getAccount(), dto.getHost(), dto.getPort()); sshSession = jSch.getSession(dto.getAccount(), dto.getHost(), dto.getPort()); sshSession.setPassword(dto.getPasswd()); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; sftp.cd(dto.getWorkingDir()); sftp.rm(dto.getFileName()); result = true; log.info("============删除文件结束=============="); } catch (JSchException e) { result = false; log.error("=====删除文件异常:{}", e.getMessage()); e.printStackTrace(); } finally { closeChannel(sftp); closeChannel(channel); closeSession(sshSession); } return result; } /** * @MonthName: download * @Description: 下载文件 * @Author: tanyp * @Date: 2022/12/19 10:38 * @Param: [dto] * @return: boolean **/ public static boolean download(UploadFileDto dto) throws Exception { log.info("============下载文件开始=============="); Boolean result = false; ChannelSftp sftp = null; Channel channel = null; Session sshSession = null; try { JSch jSch = new JSch(); jSch.getSession(dto.getAccount(), dto.getHost(), dto.getPort()); sshSession = jSch.getSession(dto.getAccount(), dto.getHost(), dto.getPort()); sshSession.setPassword(dto.getPasswd()); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; sftp.cd(dto.getWorkingDir()); sftp.get(dto.getFileName(), new FileOutputStream(new File(dto.getDownloadPath()))); sftp.disconnect(); sftp.getSession().disconnect(); result = true; log.info("============下载文件结束=============="); } catch (JSchException e) { result = false; log.error("=====下载文件异常:{}", e.getMessage()); e.printStackTrace(); } finally { closeChannel(sftp); closeChannel(channel); closeSession(sshSession); } return result; } private static void closeChannel(Channel channel) { if (channel != null) { if (channel.isConnected()) { channel.disconnect(); } } } private static void closeSession(Session session) { if (session != null) { if (session.isConnected()) { session.disconnect(); } } } }
UploadFileDto.java
package com.demo.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.InputStream; /** * @ClassName: UploadFileDto.java * @ClassPath: com.demo.dto.UploadFileDto.java * @Description: 上传文件 * @Author: tanyp * @Date: 2022/12/19 10:38 **/ @Data @AllArgsConstructor @NoArgsConstructor @Builder @ApiModel(value = "上传文件Dto") public class UploadFileDto { @ApiModelProperty(value = " ftp 服务器ip地址") private String host; @ApiModelProperty(value = " ftp 服务器port,默认是21") private Integer port; @ApiModelProperty(value = " ftp 服务器用户名") private String account; @ApiModelProperty(value = " ftp 服务器密码") private String passwd; @ApiModelProperty(value = " ftp 服务器存储图片的绝对路径") private String workingDir; @ApiModelProperty(value = "上传到ftp 服务器文件名") private String fileName; @ApiModelProperty(value = " 文件流") private InputStream inputStream; @ApiModelProperty(value = " 下载文件的路径") private String downloadPath; }
UploadVo .java
package com.demo.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @ClassName: UploadVo.java * @ClassPath: com.demo.vo.UploadVo.java * @Description: 文件VO * @Author: tanyp * @Date: 2022/12/19 15:18 **/ @Data @AllArgsConstructor @NoArgsConstructor @Builder @ApiModel(value = "文件VO") public class UploadVo { @ApiModelProperty(value = "原始文件名称") private String oldName; @ApiModelProperty(value = "新文件名称") private String newName; @ApiModelProperty(value = "访问路径") private String path; }
UploadController
package com.demo.controller; import com.demo.vo.UploadVo; import com.demo.service.UploadService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; /** * @ClassName: UploadController.java * @ClassPath: com.demo.controller.UploadController.java * @Description: 上传文件 * @Author: tanyp * @Date: 2022/12/19 15:18 **/ @Slf4j @RestController @RequestMapping("/upload") @Api(value = "upload", tags = "上传文件") public class UploadController { @Autowired private UploadService uploadService; @ApiOperation(value = "上传图片", notes = "上传图片") @PostMapping("/uploadImage") public UploadVo uploadImage(@RequestParam("file") MultipartFile file) { return uploadService.uploadImage(file); } @ApiOperation(value = "删除文件", notes = "删除文件") @GetMapping("/delFile") public Boolean delFile(String fileName) { return uploadService.delFile(fileName); } @ApiOperation(value = "下载文件", notes = "下载文件") @GetMapping("/downloadFile") public Boolean downloadFile(String fileName, String downloadPath) { return uploadService.downloadFile(fileName, downloadPath); } }
#UploadService
package com.demo.service; import com.demo.vo.UploadVo; import org.springframework.web.multipart.MultipartFile; /** * @ClassName: UploadService.java * @ClassPath: com.demo.service.UploadService.java * @Description:上传文件 * @Author: tanyp * @Date: 2022/12/19 15:18 **/ public interface UploadService { UploadVo uploadImage(MultipartFile file); Boolean delFile(String fileName); Boolean downloadFile(String fileName, String downloadPath); }
##UploadServiceImpl
package com.demo.service.impl; import com.demo.dto.UploadFileDto; import com.demo.vo.UploadVo; import com.demo.config.FtpConfig; import com.demo.service.UploadService; import com.demo.utils.UUIDUtils; import com.demo.utils.UploadFileUtils; import com.demo.exception.BusinessException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Objects; /** * @ClassName: UploadServiceImpl.java * @ClassPath: com.demo.service.impl.UploadServiceImpl.java * @Description: 上传文件 * @Author: tanyp * @Date: 2022/12/19 15:18 **/ @Slf4j @Service public class UploadServiceImpl implements UploadService { @Autowired private FtpConfig ftpConfig; @Override public UploadVo uploadImage(MultipartFile file) { log.info("=======上传图片开始,图片名称:{}", file.getOriginalFilename()); try { // 1. 取原始文件名 String oldName = file.getOriginalFilename(); // 2. ftp 服务器的文件名 String newName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + UUIDUtils.getUUID(10) + oldName.substring(oldName.lastIndexOf(".")); // 3.上传图片 Boolean result = UploadFileUtils.upload( UploadFileDto.builder() .host(ftpConfig.host) .port(ftpConfig.post) .account(ftpConfig.username) .passwd(ftpConfig.password) .workingDir(ftpConfig.basePath) .fileName(newName) .inputStream(file.getInputStream()) .build() ); // 4.返回结果 if (!result) { throw new BusinessException("上传图片失败!"); } log.info("=======上传图片结束,新图片名称:{}", newName); return UploadVo.builder() .oldName(oldName) .newName(newName) .path(ftpConfig.imageBaseUrl + "/" + newName) .build(); } catch (Exception e) { log.error("=======上传图片异常,异常信息:{}", e.getMessage()); e.printStackTrace(); } return null; } @Override public Boolean delFile(String fileName) { if (Objects.isNull(fileName)) { throw new BusinessException("文件名称为空,请核实!"); } try { Boolean result = UploadFileUtils.delete( UploadFileDto.builder() .host(ftpConfig.host) .port(ftpConfig.post) .account(ftpConfig.username) .passwd(ftpConfig.password) .workingDir(ftpConfig.basePath) .fileName(fileName) .build() ); return result; } catch (Exception e) { log.error("=======删除文件异常,异常信息:{}", e.getMessage()); e.printStackTrace(); } return null; } @Override public Boolean downloadFile(String fileName, String downloadPath) { if (Objects.isNull(fileName) || Objects.isNull(downloadPath)) { throw new BusinessException("文件名称或下载路径为空,请核实!"); } try { Boolean result = UploadFileUtils.download( UploadFileDto.builder() .host(ftpConfig.host) .port(ftpConfig.post) .account(ftpConfig.username) .passwd(ftpConfig.password) .workingDir(ftpConfig.basePath) .fileName(fileName) .downloadPath(downloadPath) .build() ); return result; } catch (Exception e) { log.error("=======下载文件异常,异常信息:{}", e.getMessage()); e.printStackTrace(); } return null; } }
FtpConfig
package com.demo.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @ClassName: FtpConfig.java * @ClassPath: com.demo.config.FtpConfig.java * @Description: FTP配置 * @Author: tanyp * @Date: 2022/12/19 22:28 **/ @Component public class FtpConfig { // ftp 服务器ip地址 @Value("${ftp.host}") public String host; // ftp 服务器port,默认是21 @Value("${ftp.post}") public Integer post; // ftp 服务器用户名 @Value("${ftp.username}") public String username; // ftp 服务器密码 @Value("${ftp.password}") public String password; // ftp 服务器存储图片的绝对路径 @Value("${ftp.base-path}") public String basePath; // ftp 服务器外网访问图片路径 @Value("${ftp.image-base-url}") public String imageBaseUrl; }
application.yml
# ftp ftp: host: 127.0.0.1 post: 22 username: ftpadmin password: ftpadmin base-path: /app/upload/images image-base-url: http://127.0.0.1:8080/images
#server {
listen 8080;
server_name localhost;
location /images/ {
root /app/upload/;
autoindex on;
}
}
登入後複製
server { listen 8080; server_name localhost; location /images/ { root /app/upload/; autoindex on; } }
以上是SpringBoot怎麼使用FTP操作文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

隨著網際網路的快速發展,檔案傳輸協定(FTP)一直是一種重要的檔案傳送方式。在Go語言中,使用FTP傳輸檔案可能是許多開發人員的需求。然而,也許很多人並不知道如何在Go語言中使用FTP。在本篇文章中,我們將探討如何在Go語言中使用FTP,從連接FTP伺服器到檔案傳輸,以及如何處理錯誤和異常。建立FTP連線在Go語言中,我們可以使用標準的"net"套件來連接FTP

一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

PHP與FTP:在網站開發中實現多個部門的文件共享隨著互聯網的發展,越來越多的企業開始借助網站平台進行資訊發布和業務推廣。然而,隨之而來的問題是如何實現多個部門之間的文件共享和協作。在這種情況下,PHP和FTP成為了最常用的解決方案之一。本文將介紹如何利用PHP和FTP在網站開發中實現多個部門的檔案分享。一、FTP介紹FTP(FileTransferPr

springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

如何用PHP實作FTP檔案上傳進度條一、背景介紹在網站開發中,檔案上傳是常見的功能。而對於大檔案的上傳,為了提高使用者體驗,我們常常需要向使用者顯示一個上傳進度條,讓使用者知道檔案上傳的進程。本文將介紹如何使用PHP實作FTP檔案上傳進度條的功能。二、FTP檔案上傳進度條的實現方法基本思路FTP檔案上傳的進度條實現,通常是透過計算上傳的檔案大小和已上傳檔案大小

如何透過PHP在FTP伺服器上進行目錄和文件的比較在web開發中,有時候我們需要比較本地文件與FTP伺服器上的文件,以確保兩者之間的一致性。 PHP提供了一些函數和類別來實作這個功能。本文將介紹如何使用PHP在FTP伺服器上進行目錄和檔案的比較,並提供相關的程式碼範例。首先,我們需要連接到FTP伺服器。 PHP提供了ftp_connect()函數來建立與FTP伺服器
