1. 程式人生 > >基於SSM框架實現利用FTP上傳檔案至Linux遠端伺服器

基於SSM框架實現利用FTP上傳檔案至Linux遠端伺服器

基於SSM框架實現利用FTP上傳檔案至Linux遠端伺服器

摘要:JavaWEB開發通常採用SSM框架,在完成web開發時經常涉及到遠端訪問Linux伺服器實現檔案上傳。通常實現檔案上傳可通過InputStream和OutputStream實現檔案讀寫操作,但對於Linux伺服器需要ftp傳輸協議來完成。
本文章將解決利用SSM框架實現利用ftp檔案傳輸協議上傳檔案至linux遠端伺服器。

  • linux安裝FTP協議
  • Java原始碼

一、linux安裝FTP協議

如果你未使用過linux伺服器,可通過騰訊雲或阿里雲等伺服器提供商購買伺服器,並完成相應安裝。
1、如果你已經安裝好FTP,直接跳到下一節,未安裝可參考:linux系統需要自主安裝FTP協議,在命令控制檯輸入

$ yum install -y vsftpd

2、安裝完畢後開啟21埠或關閉防火牆:

$ iptables -A INPUT -ptcp --dport  21 -j ACCEPT
$ chkconfig iptables off

3、安裝後的ftp還需要修改配置檔案,允許當前user(預設是root)啟用FTP:

$ vim /etc/vsftpd/vsftpd.conf

4、進入後修改或新增(允許任何使用者通過FTP操作linux):

anonymous_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES

同時修改(設定為YES表示user_list內的使用者允許訪問FTP):

dirmessage_enable=YES

5、啟動FTP

$ service vsftpd start

二、Java原始碼

實現SSM框架的上傳檔案的java原始碼如下:
1、前端檢視JSP:

<form role="form" action="addNewTask" id="singleForm" method="post" enctype="multipart/form-data">
   <div class="card-body">
      <div class="form-group">
         <label for="taskInfo">任務描述</label>
         <input type="text" class="form-control" id="taskInfo" name="taskInfo" placeholder="請填寫任務描述">
      </div>
      <div class="form-group">
         <label for="singleFile">選擇圖片</label>
         <div class="input-group">
             <div class="custom-file">
                  <input type="file" class="custom-file-input" id="singleFile" name="taskImg" onchange="checkFileKind(0)" >
                  <label class="custom-file-label" for="singleFile">選擇本地圖片</label>
             </div>  
         </div>
      </div>
   </div>
   <div class="card-footer">
      <button type="button" class="btn btn-primary" onclick="createTask(0);">建立任務</button>
      <button type="reset" class="btn btn-default">重新填寫</button>
   </div>
</form>

2、控制層Controller:

@RequestMapping(value = "/admin/taskManage/addNewTask")
	public ModelAndView addNewTask(@RequestParam("taskImg") MultipartFile taskImg, 
			@RequestParam("taskInfo") String taskInfo, ModelAndView mv,HttpSession session){
		// 根據登入名和密碼查詢使用者,判斷使用者登入
		User user = (User)session.getAttribute("user");
		if(user == null){
			mv.setView(new RedirectView("/ImgTag/login"));
			return mv;
		}
		//獲取單檔案的位元組流
		InputStream input = null;
		try {
			input = taskImg.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//設定路徑
		String uploadPath = "task/" + cellid;
		String fileName = "0.jpg";
		//上傳至linux伺服器
		UploadFileByFTP.UploadFile(input, uploadPath, fileName);
		//修改目錄許可權(可能建立的資料夾不具有寫功能,所以修改許可權)
		String order = "chmod 777 " + GetPath.getProjectRealPath() + "task/" + cellid;
		e.Compile(GetPath.hostname, GetPath.username, GetPath.password, order);
		mv.setView(new RedirectView("*****"));
		mv.setViewName("*****");
		return mv;
	}

3、Java的FTP協議(用於上傳檔案):

package com.imgtag.util;
/*
 * code by WangJianing
 * email:[email protected]
 * time:2018.11.17
 * 
 * function: upload file(s) to linux os in cloud
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.StringTokenizer;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import sun.net.ftp.FtpClient;
public class UploadFileByFTP {
	/*
	 * file:待上傳的檔案物件
	 * path:待上傳儲存的地址
	 * newFileName:儲存的檔名稱及格式
	 * 
	 * */
	public static void UploadFile(File file, String path, String newFileName){		
		//File file = new File("E:/學校檔案/軟體工程.xls");
		//String newFileName = "軟體工程.xls";
		//建立ftp客戶端
		FTPClient ftpClient = new FTPClient();
		ftpClient.setControlEncoding("GBK");
		String hostname = GetPath.hostname;
		int port = 21;
		String username = GetPath.username;
		String password = GetPath.password;
		try {
			//連結ftp伺服器
			ftpClient.connect(hostname, port);
			//登入ftp
			ftpClient.login(username, password);
			int  reply = ftpClient.getReplyCode();  
			System.out.println(reply);
			if (!FTPReply.isPositiveCompletion(reply)) {  
	        	ftpClient.disconnect();  
	            return ;  
	        }  
	        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
	        String file_path = GetPath.getProjectRealPath() + path;
	        //ftpClient.makeDirectory(file_path);//在root目錄下建立資料夾
	        StringTokenizer s = new StringTokenizer(file_path, "/");
			s.countTokens(); 
			String pathName = ""; 
			while (s.hasMoreElements()) { 
				   pathName = pathName + "/" + (String) s.nextElement(); 
				   try { 
					   ftpClient.mkd(pathName); 
				   } catch (Exception e) { 
				   } 
			} 			
	        InputStream input = new FileInputStream(file); 
	        ftpClient.storeFile(file_path + "/" + newFileName, input);/
	        input.close();  
	        ftpClient.logout();		
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally 
		{  
	        if (ftpClient.isConnected())
	        {  
	            try 
	            {  
	            	ftpClient.disconnect();  
	            } catch (IOException ioe) 
	            {  
					ioe.printStackTrace();
	            }  
	        } 
		}
	}
	/*
	 * input:待上傳的檔案位元組流
	 * path:待上傳儲存的地址
	 * newFileName:儲存的檔名稱及格式
	 * 
	 * */
	public static void UploadFile(InputStream input, String path, String newFileName){			
		//建立ftp客戶端
		FTPClient ftpClient = new FTPClient();
		ftpClient.setControlEncoding("GBK");
		String hostname = GetPath.hostname;
		int port = 21;
		String username = GetPath.username;
		String password = GetPath.password;	
		try {
			//連結ftp伺服器
			ftpClient.connect(hostname, port);
			//登入ftp
			ftpClient.login(username, password);
			int  reply = ftpClient.getReplyCode(); 
			System.out.println(reply);
			if (!FTPReply.isPositiveCompletion(reply)) {  
	        	ftpClient.disconnect();  
	            return ;  
	        }  			
	        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			String file_path = GetPath.getProjectRealPath() + path;
	        //ftpClient.makeDirectory(file_path);//在root目錄下建立資料夾
			StringTokenizer s = new StringTokenizer(file_path, "/");
			s.countTokens(); 
			String pathName = ""; 
			while (s.hasMoreElements()) { 
				   pathName = pathName + "/" + (String) s.nextElement(); 
				   try { 
					   ftpClient.mkd(pathName); 
				   } catch (Exception e) { 
				   } 
			} 						
	        ftpClient.storeFile(file_path + "/" + newFileName, input);//檔案若是不指定就會上傳到root目錄下
	        input.close();  
	        ftpClient.logout();  		
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally 
		{  
	        if (ftpClient.isConnected())
	        {  
	            try 
	            {  
	            	ftpClient.disconnect();  
	            } catch (IOException ioe) 
	            {  
					ioe.printStackTrace();
	            }  
	        } 
		}
}

4、Java遠端控制linux命令(用於遠端執行Linux命令):

package com.imgtag.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;  
import ch.ethz.ssh2.Session;  
import ch.ethz.ssh2.StreamGobbler;

public class ExecuteLinuxCmd {
	public String stateCode = "";
	public String getStateCode() {
		return stateCode;
	}
	public String executeLinuxCmd(String cmd) {
        System.out.println("got cmd job : " + cmd);
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(cmd);
            InputStream in = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(in));
            // System.out.println("[check] now size \n"+bs.readLine());
            String result = null;
            while (in.read() != -1) {
                result = bs.readLine();
                System.out.println("job result [" + result + "]");
            }
            in.close();
            // process.waitFor();
            process.destroy();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	public String Linux(String hostname,String user_id,String user_pass,String order){
		String prompt = "";
		try
		{
				/* Create a connection instance */
			Connection conn = new Connection(hostname);
			/* Now connect */
			conn.connect();
			/* Authenticate.
			 * If you get an IOException saying something like
			 * "Authentication method password not supported by the server at this stage."
			 * then please check the FAQ.
			 */
			boolean isAuthenticated = conn.authenticateWithPassword(user_id, user_pass);
			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");
			/* Create a session */
			Session sess = conn.openSession();
			sess.execCommand(order);
			System.out.println("Here is some information about the remote host:");
			/* 
			 * This basic example does not handle stderr, which is sometimes dangerous
			 * (please read the FAQ).
			 */
			InputStream stdout = new StreamGobbler(sess.getStdout());
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout,"UTF-8"))	
			int num = 0;
			while (true){
				String string = br.readLine();				
				if ("null".equals(string)||string == null||"".equals(string))
					break;
				else {
					if(num == 0){
						prompt += string;
						num = 1;
					}else {
						prompt += "\n" + string;
					}
				
				}
			}
			/* Show exit status, if available (otherwise "null") */
			System.out.println("ExitCode: " + sess.getExitStatus());
			stateCode = String.valueOf(sess.getExitStatus());
			/* Close this session */
			sess.close();
			/* Close the connection */
			conn.close();
		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			System.exit(2);
		}
		return prompt;
	}
	
	public String Compile(String hostname,String user_id,String user_pass,String order){
		String prompt = "";
		try{
			Connection conn = new Connection(hostname);
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(user_id, user_pass);
			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");
			Session sess = conn.openSession();
			sess.execCommand(order);
			System.out.println("Here is some information about the remote host:");
			StringBuffer sb = new StringBuffer();
			InputStream stdout = new StreamGobbler(sess.getStdout());
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout,"UTF-8"));
			String line = "";
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				sb.append(line).append("<br>");  
	        } 
			prompt = sb.toString();
			System.out.println("ExitCode: " + sess.getExitStatus());
			stateCode = String.valueOf(sess.getExitStatus());
			sess.close();
			conn.close();
		}
		catch (IOException e){
			e.printStackTrace(System.err);
			System.exit(2);
		}
		return prompt;
	}
}

部落格記錄著學習的腳步,分享著最新的技術,非常感謝您的閱讀,本部落格將不斷進行更新,希望能夠給您在技術上帶來幫助。