当前位置: 代码迷 >> Web前端 >> SFTP下传和上载
  详细解决方案

SFTP下传和上载

热度:342   发布时间:2012-11-22 00:16:41.0
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

....

?

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

1 楼 jayli426 2008-09-17  
大虾,请教你一个问题?
请问jftp.jar最初你是从哪个网站上下载的?
是否有最新版本啊?
能否提供一个URL啊
不胜感激啊?
2 楼 mei712 2008-11-21  
MultipartRequest和UploadedFile这两个类是那里来的啊?
3 楼 mei712 2008-11-21  
希望尽快回复!不胜感激!

支持
4 楼 Ben.Sin 2009-05-19  
回复mei712

MultipartRequest.java

package xxx;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MultipartRequest {

  private static final int DEFAULT_MAX_POST_SIZE = 1024 * 1024;  // 1 Meg

  protected Hashtable parameters = new Hashtable();  // name - Vector of values
  Hashtable files = new Hashtable();       // name - UploadedFile

  MultipartParser parser;
  String file_name="";
HttpServletRequest http_request;	
int max_post_size;
	

  public MultipartRequest(HttpServletRequest request,
                          String saveDirectory) throws IOException {
    this(request, saveDirectory, DEFAULT_MAX_POST_SIZE, null);
  }

  public MultipartRequest(HttpServletRequest request,
                          String saveDirectory,
                          int maxPostSize, String fname) throws IOException {
    // Sanity check values
    if (request == null)
      throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null)
      throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }

    // Save the dir
    File dir = new File(saveDirectory);

    // Check saveDirectory is truly a directory
    if (!dir.isDirectory())
      throw new IllegalArgumentException("Not a directory: " + saveDirectory);

    // Check saveDirectory is writable
    if (!dir.canWrite())
      throw new IllegalArgumentException("Not writable: " + saveDirectory);

    // Parse the incoming multipart, storing files in the dir provided, 
    // and populate the meta objects which describe what we found
    MultipartParser parser = new MultipartParser(request, maxPostSize, fname);
    http_request = request;
	max_post_size=maxPostSize;

    Part part;
    while ((part = parser.readNextPart()) != null) {
      String name = part.getName();
      if (part.isParam()) {
        // It's a parameter part, add it to the vector of values
        ParamPart paramPart = (ParamPart) part;
        String value = paramPart.getStringValue();
        Vector existingValues = (Vector)parameters.get(name);
        if (existingValues == null) {
          existingValues = new Vector();
          parameters.put(name, existingValues);
        }
        existingValues.addElement(value);
      }
      else if (part.isFile()) {
        // It's a file part
        FilePart filePart = (FilePart) part;
        String fileName = filePart.getFileName();
        if (fileName != null) {
          // The part actually contained a file
          filePart.writeTo(dir);
          files.put(name, new UploadedFile(
                      dir.toString(), fileName, filePart.getContentType()));
		file_name=fileName;
        }
        else { 
          // The field did not contain a file
          files.put(name, new UploadedFile(null, null, null));
        }
      }
    }
  }

  public  MultipartRequest(HttpServletRequest request,
                          int maxPostSize) throws IOException {
    // Sanity check values
    if (request == null)
      throw new IllegalArgumentException("request cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }


    // Parse the incoming multipart, storing files in the dir provided, 
    // and populate the meta objects which describe what we found
    parser = new MultipartParser(request, maxPostSize, null);
    http_request = request;
	max_post_size=maxPostSize;
}

public int checkFileSize()
{
	String err="";
	HttpServletRequest req=http_request;
    String type = null;
    String type1 = req.getHeader("Content-Type");
    String type2 = req.getContentType();
    // If one value is null, choose the other value
    if (type1 == null && type2 != null) {
      type = type2;
    }
    else if (type2 == null && type1 != null) {
      type = type1;
    }
    // If neither value is null, choose the longer value
    else if (type1 != null && type2 != null) {
      type = (type1.length() > type2.length() ? type1 : type2);
    }

    if (type == null ||
        !type.toLowerCase().startsWith("multipart/form-data")) {
      err="Posted content type isn't multipart/form-data";
    }
  // Check the content length to prevent denial of service attacks
    int length = req.getContentLength();
    if (length > max_post_size) {
      err="File size of " + length + " exceeds limit of " + max_post_size;
    }
	return length;


}
public Hashtable getAllFile() throws Exception
	{
		return files;
	}

public int getFileData() throws IOException {
	byte[]  buf=null;
	int num=0;
	
    Part part;
	long l=0;
    while ((part = parser.readNextPart()) != null) {
      String name = part.getName();
       if (part.isFile()) {
num=num+1;
        // It's a file part
        FilePart filePart = (FilePart) part;
        String fileName = filePart.getFileName();
        if (fileName != null) {
          // The part actually contained a file
           buf=filePart.getFile();
		int length = (int)buf.length;	
	//byte[] data=new byte[length];
	//System.arraycopy(data, 0, buf,0,length);
	

          //files.put(name, new UploadedFile( " ", fileName, filePart.getContentType(),data));
          files.put(fileName, new UploadedFile( "dir", fileName, filePart.getContentType(),buf));
	file_name=fileName;





        }
      }
    }
	return num;
  }


  /**
   * Constructor with an old signature, kept for backward compatibility.
   * Without this constructor, a servlet compiled against a previous version 
   * of this class (pre 1.4) would have to be recompiled to link with this 
   * version.  This constructor supports the linking via the old signature.
   * Callers must simply be careful to pass in an HttpServletRequest.
   * 
   */
  public MultipartRequest(ServletRequest request,
                          String saveDirectory) throws IOException {
    this((HttpServletRequest)request, saveDirectory);
  }

  /**
   * Constructor with an old signature, kept for backward compatibility.
   * Without this constructor, a servlet compiled against a previous version 
   * of this class (pre 1.4) would have to be recompiled to link with this 
   * version.  This constructor supports the linking via the old signature.
   * Callers must simply be careful to pass in an HttpServletRequest.
   * 
   */
  public MultipartRequest(ServletRequest request,
                          String saveDirectory,
                          int maxPostSize) throws IOException {
    this((HttpServletRequest)request, saveDirectory, maxPostSize, null);
  }

  /**
   * Returns the names of all the parameters as an Enumeration of 
   * Strings.  It returns an empty Enumeration if there are no parameters.
   *
   * @return the names of all the parameters as an Enumeration of Strings.
   */
  public Enumeration getParameterNames() {
    return parameters.keys();
  }

  /**
   * Returns the names of all the uploaded files as an Enumeration of 
   * Strings.  It returns an empty Enumeration if there are no uploaded 
   * files.  Each file name is the name specified by the form, not by 
   * the user.
   *
   * @return the names of all the uploaded files as an Enumeration of Strings.
   */
  public Enumeration getFileNames() {
    return files.keys();
  }
  public String getFileName() {
    return file_name;
  }

  /**
   * Returns the value of the named parameter as a String, or null if 
   * the parameter was not sent or was sent without a value.  The value 
   * is guaranteed to be in its normal, decoded form.  If the parameter 
   * has multiple values, only the last one is returned (for backward 
   * compatibility).  For parameters with multiple values, it's possible
   * the last "value" may be null.
   *
   * @param name the parameter name.
   * @return the parameter value.
   */
  public String getParameter(String name) {
    try {
      Vector values = (Vector)parameters.get(name);
      if (values == null || values.size() == 0) {
        return null;
      }
      String value = (String)values.elementAt(values.size() - 1);
      return value;
    }
    catch (Exception e) {
      return null;
    }
  }

  /**
   * Returns the values of the named parameter as a String array, or null if 
   * the parameter was not sent.  The array has one entry for each parameter 
   * field sent.  If any field was sent without a value that entry is stored 
   * in the array as a null.  The values are guaranteed to be in their 
   * normal, decoded form.  A single value is returned as a one-element array.
   *
   * @param name the parameter name.
   * @return the parameter values.
   */
  public String[] getParameterValues(String name) {
    try {
      Vector values = (Vector)parameters.get(name);
      if (values == null || values.size() == 0) {
        return null;
      }
      String[] valuesArray = new String[values.size()];
      values.copyInto(valuesArray);
      return valuesArray;
    }
    catch (Exception e) {
      return null;
    }
  }

  /**
   * Returns the filesystem name of the specified file, or null if the 
   * file was not included in the upload.  A filesystem name is the name 
   * specified by the user.  It is also the name under which the file is 
   * actually saved.
   *
   * @param name the file name.
   * @return the filesystem name of the file.
   */
  public String getFilesystemName(String name) {
    try {
      UploadedFile file = (UploadedFile)files.get(name);
      return file.getFilesystemName();  // may be null
    }
    catch (Exception e) {
      return null;
    }
  }

  /**
   * Returns the content type of the specified file (as supplied by the 
   * client browser), or null if the file was not included in the upload.
   *
   * @param name the file name.
   * @return the content type of the file.
   */
  public String getContentType(String name) {
    try {
      UploadedFile file = (UploadedFile)files.get(name);
      return file.getContentType();  // may be null
    }
    catch (Exception e) {
      return null;
    }
  }

  /**
   * Returns a File object for the specified file saved on the server's 
   * filesystem, or null if the file was not included in the upload.
   *
   * @param name the file name.
   * @return a File object for the named file.
   */
  public File getFile(String name) {
    try {
      UploadedFile file = (UploadedFile)files.get(name);
      return file.getFile();  // may be null
    }
    catch (Exception e) {
      return null;
    }
  }
}

/********
// A class to hold information about an uploaded file.
//
class UploadedFile {

  private String dir;
  private String filename;
  private String type;
private byte[] data;

  UploadedFile(String dir, String filename, String type, byte[] data) {
    this.dir = dir;
    this.filename = filename;
    this.type = type;
	this.data=data;
  }
  UploadedFile(String dir, String filename, String type) {
    this.dir = dir;
    this.filename = filename;
    this.type = type;
  }
	public byte[] getData()
	{
		return data;
	}

  public String getContentType() {
    return type;
  }

  public String getFilesystemName() {
    return filename;
  }

  public File getFile() {
    if (dir == null || filename == null) {
      return null;
    }
    else {
      return new File(dir + File.separator + filename);
    }
  }
}
****/




UploadFile.java
package xxx;
import java.io.*;


// A class to hold information about an uploaded file.
//
public class UploadedFile {

  private String dir;
  private String filename;
  private String type;
private byte[] data;

  UploadedFile(String dir, String filename, String type, byte[] data) {
    this.dir = dir;
    this.filename = filename;
    this.type = type;
        this.data=data;
  }
  UploadedFile(String dir, String filename, String type) {
    this.dir = dir;
    this.filename = filename;
    this.type = type;
  }
        public byte[] getData()
        {
                return data;
        }

  public String getContentType() {
    return type;
  }

  public String getFilesystemName() {
    return filename;
  }

  public File getFile() {
    if (dir == null || filename == null) {
      return null;
    }
    else {
      return new File(dir + File.separator + filename);
    }
  }
}