- 浏览: 234234 次
- 性别:
- 来自: 广州
文章分类
最新评论
-
test_lockxxx:
mythal 写道不好意思,StringUtils.split ...
String.split()和StringTokenizer和indexOf()的比较 -
grantbb:
受用,支持!
Javamail 发送附件中文名乱码问题解决 -
kensunhu:
for(File attach:attachments){
...
Javamail 发送附件中文名乱码问题解决 -
Ben.Sin:
liupeng_10408 写道博主,你好!我开发的是andr ...
Javamail读取邮件列表出现OutOfMemery -
liupeng_10408:
博主,你好!我开发的是android版邮件系统。
只写了如下几 ...
Javamail读取邮件列表出现OutOfMemery
维护一个旧项目(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
....
这个问题我是不怎么好理解...
- jftp.jar (2.4 MB)
- 描述: 开源包
- 下载次数: 321
评论
4 楼
Ben.Sin
2009-05-19
回复mei712
MultipartRequest.java
UploadFile.java
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); } } }
3 楼
mei712
2008-11-21
希望尽快回复!不胜感激!
支持
支持
2 楼
mei712
2008-11-21
MultipartRequest和UploadedFile这两个类是那里来的啊?
1 楼
jayli426
2008-09-17
大虾,请教你一个问题?
请问jftp.jar最初你是从哪个网站上下载的?
是否有最新版本啊?
能否提供一个URL啊
不胜感激啊?
请问jftp.jar最初你是从哪个网站上下载的?
是否有最新版本啊?
能否提供一个URL啊
不胜感激啊?
发表评论
-
【转】Java Out of Memory 分析
2013-08-02 00:55 938一、内存溢出类型 ... -
Spring3 MVC REST + JPA2 (Hibernate 3.6.1) 构建投票系统 - 3. JPA2(Hibernate实现)
2011-03-29 00:56 1803上一篇介绍了如何使用Spring MVC搭建REST的web应 ... -
Spring3 MVC REST + JPA2 (Hibernate 3.6.1) 构建投票系统 - 2.Spring MVC REST
2011-03-27 00:03 3228前言 :本文只阐述如何使用Spring MVC做REST应用 ... -
传说中的投票系统
2011-03-15 02:35 0传说中的投票系统 -
Spring3 MVC REST + JPA2 (Hibernate 3.6.1) 构建投票系统 - 1.序
2011-03-14 21:37 2674屈指算算,做J2EE开发已经有超过5个年头有多了,技术的东西跟 ... -
If..else, Map, Enum查询速度对比
2011-03-04 23:27 1625习惯每天逛一下论坛,今天发现一个关于重构的帖子 http:/ ... -
[转]Java虚拟机(JVM)参数配置说明
2010-09-16 22:54 1111Java虚拟机(JVM)参数配置说明 在J ... -
使用StringBuffer和StringBuilder代替String的+运算
2010-05-05 16:14 1265使用StringBuffer和StringBuilder代替S ... -
String.split()和StringTokenizer和indexOf()的比较
2010-05-05 15:52 6214将字符串按照一定的规 ... -
【转】Java中的UDP协议编程
2010-03-04 00:38 1735一. UDP协议定义 UDP ... -
iBatis异常There is no statement named update in this SqlMap.
2009-10-26 09:39 4551最近使用iBatis搭建项目架构的时候遇到了一个异常,如下文所 ... -
Spring配置iBatis多个SqlMapConfig.xml
2009-10-23 15:42 4172Spring粘合iBatis的时候需要配置iBatis的Sql ... -
Javamail在解析附件是抛出Missing start boundary异常
2009-09-04 17:45 9609在做javamail通过pop3解析邮件的时候,在解析邮件包含 ... -
Javamail 的AuthenticationFailedException异常
2009-09-04 10:43 2291Javamail接收用pop3协议接收邮件的时候,我们可以通过 ... -
Spring 定时器使用
2009-07-15 14:36 2703【原文】http://nighthun.itpub.net/p ... -
字符串转化为unicode编码
2009-04-28 11:42 1582字符串转化为unicode编码 package com ... -
项目由OC4J 9i升级到OC4J10g
2008-04-27 18:45 1487最近项目eJMS需要由oc4j 9 ... -
Java日积月累001-字符串比较的技巧,避免NullPointerException
2008-04-16 23:33 1329这里说的String的比较是value的比较,通过equals ... -
Tomcat设置Session time out的时间
2007-04-11 11:48 3944在Tomcat中的conf/web.xml可以找到以下scri ... -
动态配置log4j
2007-09-04 11:10 3982看到好的文章,收录以备学习之用。文章来源于http://www ...
相关推荐
本资源包含实现JAVA SFTP上传和下载功能所需的JAR文件和源码,这对于开发者来说是非常有价值的。 首先,我们需要了解Java中实现SFTP的主要库:JSch(Java Secure Channel)。JSch是一个开源库,它实现了SSH2协议,...
在.NET 2.0时代,若要实现在Visual Studio 2005中进行SFTP上传和下载,开发者通常需要借助第三方库,因为.NET Framework 2.0的标准库并未内置对SFTP的支持。这个“NET 2.0 支持SFTP上传和下载的dll文件”很可能是...
C# WinForm通过Renci.SshNet和Tamir.SharpSsh进行SFTP文件上传和下载 一、使用Renci.SshNet文件上传和下载 二、使用Tamir.SharpSsh文件上传和下载 C#源代码
"SFTP上传下载文件工具"通常指的是支持SFTP协议的软件应用,这些应用使得用户能够方便地在本地计算机和远程服务器之间进行文件的上传和下载。描述中提到的"可直接文件夹传输"功能,意味着这款工具不仅支持单个文件的...
#!/usr/bin/python # -*- coding:utf-8 -*- ...import os,sys import paramiko #创建transport对象 t = paramiko.Transport(('192.168.56.102',22)) #连接服务器 #创建sftp对象 ...# 将sftp.txt下载到本机桌面
在Java编程中,SFTP(Secure File ...综上所述,Java操作SFTP上传和下载文件主要涉及到JSch库的使用,包括连接配置、通道创建、文件操作以及断开连接等步骤。在实际开发中,应结合具体需求,优化代码并确保安全性。
首先,让我们详细了解一下SFTP上传和下载的流程。在Java中,我们可以使用开源库JSch来实现SFTP操作。JSch库提供了连接到SFTP服务器、创建会话、打开通道、传输文件等方法。上传文件通常涉及以下步骤: 1. 创建JSch...
linux脚本sftp上传文件
本项目“SFTP上传下载 MFC VS2010”专注于利用MFC(Microsoft Foundation Classes)库在Visual Studio 2010环境下实现SFTP的上传和下载功能。 MFC是微软提供的C++类库,它为Windows应用程序开发提供了丰富的接口,...
在Android平台上实现SFTP(Secure File Transfer Protocol,安全文件传输协议)上传和下载功能,是移动应用中处理远程文件操作的常见需求。SFTP是一种基于SSH的安全文件传输协议,它提供了在不安全网络环境中安全...
JAVA SFTP文件上传、下载及批量下载实例 在本篇文章中,我们将详细介绍JAVA SFTP文件上传、下载及批量下载的实例,包括相关的概念、API介绍、代码实现等方面的内容。 首先,我们需要了解什么是SFTP?SFTP(Secure ...
标签中的“sftp上传下载”和“java sftp”强调了这个主题主要关注Java语言中使用SFTP协议进行文件传输的实践。提供的压缩包文件“sftp上传下载”可能包含了实现这些功能的示例代码或更完整的解决方案,可以帮助...
在本文中,我们将深入探讨如何使用C#编程语言和Renci.SshNet库来实现SFTP(Secure File Transfer Protocol)文件的上传与下载,并且在操作过程中添加进度条功能。SFTP是一种安全的网络协议,用于在客户端和服务器...
该工具支持ftp和sftp的上传和下载 1
在Windows平台上进行FTP(文件传输协议)和SFTP(安全文件传输协议)的文件与文件夹的下载和上传,通常需要使用特定的库来实现。本项目提供的是一套完整的C++工程源代码,包含了FTP和SFTP的客户端功能,便于开发者在...
以下是使用C#进行SFTP上传文件的基本步骤: 1. 引用库: ```csharp using Renci.SshNet; ``` 2. 创建SFTP客户端对象并设置连接参数: ```csharp var sshClient = new SftpClient("sftp服务器地址", "用户名",...
前面上传过一次,不能编辑了,重新上传...和前面那个相比,代码优化了一下:1)上传和下载完成的时候关闭FileStream(不关闭的话下载完成之后本地操作该文件会提示被占用),2)增加了连续下载多个文件(位于Form2)。