安装ftp服务
yum install -y vsftpd
查看一下是否安装成功
rpm -qa |grep ‘vsftpd’
ftp的配置文件主要有三个,位于/etc/vsftpd/目录下,分别是:
ftpusers:用来指定哪些用户不能访问ftp服务器
user_list::这个文件中的用户是否可以登录到服务器,取决于vsftpd.conf文件中的userlist_enable和userlist_deny这两个选项。
vsftpd.conf:ftp服务器的主配置文件
添加ftp用户(上传的时候有用)
useradd -d /data/ftp -s /sbin/nologin ftpuser
用户配置密码,需要在root用户下
passwd ftpuser
xxx
启动服务
#启动ftp命令
service vsftpd start
#停止ftp命令
service vsftpd stop
#重启ftp命
service vsftpd restart
#重载
service vsftpd reload
修改ftp配置 注释可以忽略,看看最下面增加的配置就行
# 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
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode. The vsftpd.conf(5) man page explains
# the behaviour when these options are disabled.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
#ftpd_banner=Welcome to blah FTP service.
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd/banned_emails
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
#chroot_local_user=YES
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd/chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=NO
#
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuration
# files.
# Make sure, that one of the listen options is commented !!
listen_ipv6=YES
pam_service_name=vsftpd
userlist_enable=YES
pam_service_name=vsftpd
userlist_enable=YES
userlist_deny=no
userlist_file=/etc/vsftpd/user_list
别忘记在用户列表文件 user_list 加上自己的用户名 ftpuser
# vsftpd userlist
# If userlist_deny=NO, only allow users in this file
# If userlist_deny=YES (default), never allow users in this file, and
# do not even prompt for a password.
# Note that the default vsftpd pam config also checks /etc/vsftpd/ftpusers
# for users that are denied.
#root
#bin
#daemon
#adm
#lp
#sync
#shutdown
#halt
#mail
#news
#uucp
#operator
#games
#nobody
ftpuser
下面是上传ftp的java程序
//利用ftp技术,将文件上传到ftp服务器
@CrossOrigin(origins = "*") // 允许任何来源的请求
@PostMapping("/uploadFileToFTP")
//ftp 上传方法
public boolean uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("batchId") String batchId) throws IOException {
boolean flag = uploadFile(FTPProperties.getServer(), FTPProperties.getPort(), FTPProperties.getUsername(),
FTPProperties.getPassword(), batchId, "video", file.getOriginalFilename(), file.getInputStream());
//根据反馈输出日志
if (flag) {
log.info("上传成功,文件名为:" + file.getOriginalFilename() + "文件大小=" + file.getSize() + "字节" + "MB=" + file.getSize() / 1024 / 1024 + "MB");
} else {
log.error("上传失败,文件名为:" + file.getOriginalFilename() + "文件大小=" + file.getSize() + "字节" + "MB=" + file.getSize() / 1024 / 1024 + "MB");
}
return flag;
}
/**
* #!/bin/bash
* <p>
* # 安装vsftpd
* sudo yum remove vsftpd -y
* sudo yum install vsftpd -y
* <p>
* # 启动vsftpd服务
* sudo systemctl start vsftpd
* <p>
* # 检查服务状态
* sudo systemctl status vsftpd
* 云服务器记得开端口
* <p>
* 创建一个新用户
* 切记 必须在/etc/vsftpd/user_list
* <p>
* 指定允许使用vsftpd的用户列表文件=》 也就是自己的用户名,要不然访问530错误
*
* @param url
* @param port
* @param username
* @param password
* @param path
* @param path1
* @param filename
* @param input
* @return
*/
public boolean uploadFile(String url,// FTP服务器hostname
int port,// FTP服务器端口
String username, // FTP登录账号
String password, // FTP登录密码
String path, // FTP服务器保存目录
String path1, // FTP服务器保存目录1
String filename, // 上传到FTP服务器上的文件名
InputStream input // 输入流
) {
boolean success = false;
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
try {
boolean b = false;
int reply;
ftp.connect(url, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();// 获取服务器的响应码。
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.makeDirectory(path); //创建文件夹
ftp.changeWorkingDirectory(path); //切换到文件夹
// ftp.makeDirectory(path1);
// ftp.changeWorkingDirectory(path1);
b = ftp.storeFile(filename, input);//最终默认上传到 /home/ftpuser 目录下 批次id目录内
if (b) {
//异步写入日志
asynWriteVideoImportLog(path, filename, input);
}
input.close();
ftp.logout();
success = b;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
@Async("normalThreadPool")
public void asynWriteVideoImportLog(String path, String filename, InputStream input) throws IOException {
//写入日志
FtpImportTableEntity ftpImportTableEntity = new FtpImportTableEntity();
ftpImportTableEntity.setFileName(filename);
ftpImportTableEntity.setAddress(path + "/" + filename);
ftpImportTableEntity.setSize((int) input.available());
ftpImportTableEntity.setTester(filename.split("_")[1]);
ftpImportTableEntity.setTime(LocalDateTime.now());
ftpImportTableEntity.setBatch(Long.parseLong(path));
ftpImportTableService.save(ftpImportTableEntity);
}
@CrossOrigin(origins = "*") // 允许任何来源的请求
@GetMapping("/ftp/getVideo")
public void getVideo(HttpServletResponse response, @RequestParam String videoPath, @RequestParam String videoName) {
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
try {
ftp.connect(FTPProperties.getServer(), FTPProperties.getPort());
ftp.login(FTPProperties.getUsername(), FTPProperties.getPassword());
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
throw new RuntimeException("FTP server refused connection.");
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream inputStream = ftp.retrieveFileStream(videoPath + "/" + videoName);
if (inputStream != null) {
try (OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush(); // 确保所有数据已写入输出流
}
// 关闭输出流
response.flushBuffer();
inputStream.close();
ftp.logout(); // 登出
} else {
throw new RuntimeException("文件未找到");
}
} catch (IOException e) {
// throw new RuntimeException("Error downloading file from FTP server", e);
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
// log error or handle as needed
}
}
}
}
@CrossOrigin(origins = "*") // 允许任何来源的请求
@GetMapping("/ftp/getVideoList")
public List<VideoInfo> getVideoList() {
List<VideoInfo> videoList = new ArrayList<>();
// 连接FTP服务器
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
try {
int reply;
ftp.connect(FTPProperties.getServer(), FTPProperties.getPort());
ftp.login(FTPProperties.getUsername(), FTPProperties.getPassword());
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
FTPFile[] files = ftp.listFiles(); // 获取FTP服务器上所有文件
for (FTPFile file : files) {
listFilesRecursive(ftp, "/home/ftpuser", videoList);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return videoList;
}
private void listFilesRecursive(FTPClient ftp, String path, List<VideoInfo> videoList) throws IOException {
FTPFile[] files = ftp.listFiles(path);
for (FTPFile file : files) {
if (file.isDirectory()) {
// 如果是文件夹,递归进入文件夹
listFilesRecursive(ftp, path + "/" + file.getName(), videoList);
} else if (file.getName().toLowerCase().endsWith(".mp4")) {
// 处理视频文件
String videoPath = path; // 视频文件路径
String videoName = file.getName(); // 视频文件名称
videoList.add(new VideoInfo(videoPath, videoName));
}
}
}
上传文件是默认存在/home/ftpuser里的,程序里你定义什么文件夹,都会在/home/ftpuser内进行,下面如果你想指定ftp上传那个文件夹怎么办?
下面是如何修改配置,让其可以传到指定文件夹:
命令行三行即可,假如我想把上传的视频配置到nginx的文件目录下,
#修改指定用户的指定文件目录
usermod -d /home/nginx/www/images ftpuser
#
#给权限
chown -R ftpuser:ftpuser /home/nginx/www/images
#重启
systemctl restart vsftpd.service
想知道我怎么让其使用nginx部署视频播放服务器,请看我的另一篇文章
《nginx部署视频服务(视频下载链接也ok),vue前端如何播放视频》