SFTP上传和下载

维护一个旧项目(eJMS),先前从JDK1.3升级到1.5,后来还要从FTP转换到SFTP

转SFTP用了一个开源的jftp.jar包支持,download的代码

public byte[] downloadFile(String remoteDir, String fileName){
	Session session;
	Channel channel;
	JSch jsch = new JSch();
		
	try {
		session = jsch.getSession(this.userName, this.hostName, this.port);
		System.out.println("Get Session : " + session);
		session.setPassword(password);
		System.out.println("set password ... ");
		session.setUserInfo(defaultUserInfo);
		System.out.println("set user info ... ");
		session.connect();
		System.out.println("connected session : sftp://" + this.hostName + ":" + this.port);
		channel = session.openChannel("sftp");
		System.out.println("opened channel ... ");
		channel.connect();
		System.out.println("connected channel ... ");
		ChannelSftp c = (ChannelSftp)channel;
		System.out.println("remoted channel ... ");
		
		c.cd(remoteDir);
		Vector getFile = new Vector();
		InputStream in = c.get(fileName);
		int length = 0;
		int totalLength = 0;
		
		byte[] buffer = new byte[1024];
		while ((length = in.read(buffer)) > 0){
			byte[] tmpBuffer = new byte[length];
			System.arraycopy(buffer, 0, tmpBuffer, 0, length);
			getFile.addElement(tmpBuffer);
			totalLength = totalLength + length;
		}
		in.close();
		
		byte[] result = new byte[totalLength];
		int pos = 0;
		for (int i = 0; i < getFile.size(); i ++){
			byte[] tmpBuffer = (byte[])getFile.elementAt(i);
			System.arraycopy(tmpBuffer, 0, result, pos, tmpBuffer.length);
			pos = pos + tmpBuffer.length;
		}
		getFile.clear();
		
		System.out.println("downloaded file '" + remoteDir + "\\" + fileName + "'");
		
		c.disconnect();
		System.out.println("disconnected channel ... ");
		
		session.disconnect();
		System.out.println("disconnected session ... ");
		
		return result;
	} catch (JSchException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SftpException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return null;
}

 调用download的方法

public byte[] getFile(String server, String user, String pwd, String tar_dir, String filename)	{
	if(server!=null && user != null && pwd!=null) {
		SFtp sftp = new SFtp(server, user, pwd);
		return sftp.downloadFile(tar_dir, filename);
	} else {
	    return null;
	}
}

 上传的代码

public boolean uploadFile(String remoteDir, String fileName, byte[] data){
	Session session;
	Channel channel;
	JSch jsch = new JSch();

	try {
		session = jsch.getSession(this.userName, this.hostName, this.port);
		System.out.println("Get Session : " + session);
		session.setPassword(password);
		System.out.println("set password ... ");
		session.setUserInfo(defaultUserInfo);
		System.out.println("set user info ... ");
		session.connect();
		System.out.println("connected session : sftp://" + this.hostName + ":" + this.port);

		channel = session.openChannel("sftp");
		System.out.println("opened channel ... ");
		channel.connect();
		System.out.println("connected channel ... ");
		ChannelSftp c = (ChannelSftp)channel;
		System.out.println("remoted channel ... ");
		
		c.cd(remoteDir);
		OutputStream out = c.put(fileName);
		int length = data.length;
		
		out.write(data, 0, length);
		out.flush();
		out.close();
		
		System.out.println("uploaded file to '" + remoteDir + "\\" + fileName + "'");
		
		c.disconnect();
		System.out.println("disconnected channel ... ");
		
		session.disconnect();
		System.out.println("disconnected session ... ");
		
		return true;
	} catch (JSchException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SftpException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return false;
}

 调用上传的方法的部分代码

public int getUploadFile(HttpServletRequest request, int maxSize){ 
	maxsize = maxSize;
	int length=0;

	try {
	        // Setup incoming data
		multi = new MultipartRequest(request, 1024*1024*10);
		int flength = multi.checkFileSize();
		    
		// check file's length
		if(flength > (maxSize * 1024)){
		    	return -1;
		}

    		multi.getFileData();
	    	Hashtable all=multi.getAllFile();
		Enumeration files = all.elements();
		    
		while(files.hasMoreElements()) {
    			UploadedFile up = (UploadedFile)files.nextElement();
    			
    			// upload file must be *.doc
        	        if (!up.getFilesystemName().toLowerCase().endsWith(".doc")){
                		return -2;
	                }
			byte[] data = up.getData();
			log(server+", "+user+","+pwd+","+tar_dir+","+filename);
			    
			SFtp sftp = new SFtp(server, portNo, user, pwd);
			
			if (sftp.uploadFile(tar_dir, filename, data)  == true){
				    length = length + data.length;
			}else{
				log("ftp file error:" + filename);
			}
    		}
    	} catch (Exception e) {
    		log(e, "upload error"); 
    		return 0;
        }
	return length; 
}

上传的时候直接call JavaBean就可以了

下载的时候由于返回的是byte[],所以call JavaBean之后还需要返回给客户端

ServletOutputStream outs = response.getOutputStream();

outs.write(data);

outs.flush();

outs.close();

 

这里还要注意一个问题,当你引入一些package或者其他定义之类的代码,它们之间不可以存在有空格

比如这样没有问题

<%%><%%><%

...

%>

但是如果是

<%%>

<%

...

%>

就会抛出异常

2008-5-6 15:17:01 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response

....

 

这个问题我是不怎么好理解...

你可能感兴趣的:(C++,c,servlet,C#,UP)