基于SSM框架实现利用FTP上传文件至Linux远程服务器

版权声明:版权所有,尊重原创。转载请注明出处: https://blog.csdn.net/qq_36426650/article/details/84347460

基于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;
	}
}

博客记录着学习的脚步,分享着最新的技术,非常感谢您的阅读,本博客将不断进行更新,希望能够给您在技术上带来帮助。

猜你喜欢

转载自blog.csdn.net/qq_36426650/article/details/84347460