Java FtpClient 實現檔案上傳服務,ftpclient檔案上傳
一、Ubuntu 安裝 Vsftpd 服務
1、安裝
sudo apt-get install vsftpd
2、添加使用者(uftp)
sudo useradd -d /home/uftp -s /bin/bash uftp
3、設定使用者密碼
sudo useradd -d /home/uftp -s /bin/bash uftp
4、建立使用者目錄
sudo mkdir /home/uftp
5、設定使用者密碼
sudo passwd uftp
6、設定/etc/vsftpd.conf設定檔
sudo vim /etc/vsftpd.conf
a、修改上傳檔案的許可權:
這裡會有一個問題,預設情況下的預設許可權是 077 也就是對應Linux 中的700 計算規則是 linux 的許可權 777 - local_umask
如果沒有設定local_umask 檔案許可權,會導致上傳之後的檔案,我們無法通過伺服器訪問(缺少許可權)
b、在設定檔末尾添加:
userlist_deny=NOuserlist_enable=YESuserlist_file=/etc/allowed_usersseccomp_sandbox=NOlocal_enable=YES
c、設定上傳檔案許可權:
write_enable = YES
這裡如果不設定成YES 預設情況下不允許上傳檔案。
7、建立/etc/allowed_users
添加允許任務加入到檔案中,
8、重啟服務
sudo service vsftpd restart
9、使用XFTP 測試連接
使用XFtp 建立一個新的串連,這裡需要注意選擇的協議ftp,連接埠是21,在填寫好帳號密碼之後,即可以串連我們的伺服器。
測試上傳檔案:
這裡上傳了一個txt 檔案,我們可以看到檔案的許可權是666,這裡主要就是因為我們設定了上傳檔案之後的許可權 local_umask.
二、Java FtpClient 實現檔案上傳
1、Maven 依賴
<!-- Apache工具組件 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> </dependency>
2、建立FtpClient 對象遠端連線伺服器
FTPClient ftp = new FTPClient(); //連結遠程服務 ftp.connect("192.168.148.128", 21);
串連結果可以debug 看到:
3、FtpClient 登入伺服器
ftp.login("uftp", "**"); //返回登入結果狀態 int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ; }
我們可以通過判斷replyCode 和replyString 來查看使用者是否登入成功!
4、修改檔案上傳路徑和檔案類型
//修改上傳檔案路徑 ftp.changeWorkingDirectory("/home/uftp/images/"); //修改檔案類型 ftp.setFileType(FTP.BINARY_FILE_TYPE);
5、上傳檔案
//擷取上傳檔案的輸入資料流 FileInputStream fileInputStream = new FileInputStream(new File("D:/123.jpg")); //把檔案推到伺服器上 ftp.storeFile("hello.jpg", fileInputStream);
上傳檔案完成之後,通過查看返回結果判斷時候上傳成功
6、退出登入
//退出登入 ftp.logout();
以上步驟就是使用FtpClient完成了一次檔案上傳操作。
三、使用Nginx 查看伺服器圖片
1、nginx 設定檔
在server 中添加 圖片位址解析
location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt)${ root /home/uftp/images; expires 7d; }
2、重啟Nginx
./nginx -s reload
3、查看圖片
http://192.168.148.128/hello.jpg
總結:到這裡我們就完成了一個簡單的圖片上傳到伺服器,並且展示的小demo,配置過程中主要碰到的問題是關於檔案許可權的問題,如果沒有設定vsftpd 中的設定檔中local_umask,即使我們成功上傳了檔案,也無法使用nginx 進行瀏覽,設定write_enable = YES 保證檔案能夠上傳。