javaftp上传文件(进度条显示进度)

ScumVirus ScumVirus     2022-11-30     387

关键词:

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">java实现FTP上传有2种方式,一种是org.apache.commons.net.ftp.FTPClient这个jar包,一种是sun.net.ftp.FtpClient。不知道为什么,在使用前一种方式时,在遇到大批量的上传文件时总会抛出异常,我却找不出原因,所以使用的是后者。</span>
sun的FtpClient就在自带的system library中,如果程序找不到,Remove一下system library,再重新添加一次就好。
这边我套用的是别人封装好的方法进行上传的,只不过稍加修改,再上传之前计算了一下所选文件(夹)的总大小,然后单独开了一个线程每隔一段时间计算总的上传量,然后刷新swing界面UI。这边直接贴上FtpClient封装好后的类的代码:
java实现FTP上传有2种方式,一种是org.apache.commons.net.ftp.FTPClient这个jar包,一种是sun.net.ftp.FtpClient。不知道为什么,在使用前一种方式时,在遇到大批量的上传文件时总会抛出异常,我却找不出原因,所以使用的是后者。

sun的FtpClient就在自带的system library中,如果程序找不到,Remove一下system,再重新添加一遍就好。

下面主要贴上封装好的FtpUtils类的代码:

package com.fisee.ftp;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
 * ftp上传,下载
 * 
 * @author why 2009-07-30
 * 
 */
public class FtpUtils 

	private String ip = "";

	private String username = "";

	private String password = "";

	private int port = -1;

	private String path = "";

	FtpClient ftpClient = null;

	OutputStream os = null;

	FileInputStream is = null;
	
	public static long trans = 0;//已传输文件大小
	public static long totalSize = 0;//文件总大小

	public FtpUtils(String serverIP, int port, String username, String password) 
		this.ip = serverIP;
		this.username = username;
		this.password = password;
		this.port = port;
		trans = 0;
	

	/**
	 * 连接ftp服务器
	 * 
	 * @throws IOException
	 */
	public boolean connectServer() 
		ftpClient = new FtpClient();
		try 
			if (this.port != -1) 
				ftpClient.openServer(this.ip, this.port);
			 else 
				ftpClient.openServer(this.ip);
			
			ftpClient.login(this.username, this.password);
			if (this.path.length() != 0) 
				ftpClient.cd(this.path);// path是ftp服务下主目录的子目录
			
			ftpClient.binary();// 用2进制上传、下载
			System.out.println("已登录到\\"" + ftpClient.pwd() + "\\"目录");
			return true;
		 catch (IOException e) 
			e.printStackTrace();
			return false;
		
	

	/**
	 * 断开与ftp服务器连接
	 * 
	 * @throws IOException
	 */
	public boolean closeServer() 
		try 
			if (is != null) 
				is.close();
			
			if (os != null) 
				os.close();
			
			if (ftpClient != null) 
				ftpClient.closeServer();
			
			System.out.println("已从服务器断开");
			return true;
		 catch (IOException e) 
			e.printStackTrace();
			return false;
		
	

	/**
	 * 检查文件夹在当前目录下是否存在
	 * 
	 * @param dir
	 * @return
	 */
	private boolean isDirExist(String dir) 
		String pwd = "";
		try 
			pwd = ftpClient.pwd();
			ftpClient.cd(dir);
			ftpClient.cd(pwd);
		 catch (Exception e) 
			return false;
		
		return true;
	

	/**
	 * 在当前目录下创建文件夹
	 * 
	 * @param dir
	 * @return
	 * @throws Exception
	 */
	private boolean createDir(String dir) 
		try 
			ftpClient.ascii();
			StringTokenizer s = new StringTokenizer(dir, "/"); // sign
			s.countTokens();
			String pathName = ftpClient.pwd();
			while (s.hasMoreElements()) 
				pathName = pathName + "/" + (String) s.nextElement();
				try 
					ftpClient.sendServer("MKD " + pathName + "\\r\\n");
				 catch (Exception e) 
					e = null;
					return false;
				
				ftpClient.readServerResponse();
			
			ftpClient.binary();
			return true;
		 catch (IOException e1) 
			e1.printStackTrace();
			return false;
		
	

	/**
	 * ftp上传 如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
	 * 
	 * @param filename
	 *            要上传的文件(或文件夹)名
	 * @return
	 * @throws Exception
	 */
	public boolean upload(String filename) 
		String newname = "";
		if (filename.indexOf("/") > -1) 
			newname = filename.substring(filename.lastIndexOf("/") + 1);
		 else 
			newname = filename;
		
		return upload(filename, newname);
	

	/**
	 * ftp上传 如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换
	 * 
	 * @param fileName
	 *            要上传的文件(或文件夹)名
	 * @param newName
	 *            服务器段要生成的文件(或文件夹)名
	 * @return
	 */
	public boolean upload(String fileName, String newName) 
		try 
			/*String savefilename = new String(fileName.getBytes("ISO-8859-1"),
					"GBK");*/
			String savefilename = fileName;
			File file_in = new File(savefilename);// 打开本地待长传的文件
			if (!file_in.exists()) 
				throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
			
			if (file_in.isDirectory()) 
				upload(file_in.getPath(), newName, ftpClient.pwd());
			 else 
				uploadFile(file_in.getPath(), newName);
			

			if (is != null) 
				is.close();
			
			if (os != null) 
				os.close();
			
			return true;
		 catch (Exception e) 
			e.printStackTrace();
			System.err.println("Exception e in Ftp upload(): " + e.toString());
			return false;
		 finally 
			try 
				if (is != null) 
					is.close();
				
				if (os != null) 
					os.close();
				
			 catch (IOException e) 
				e.printStackTrace();
			
		
	

	/**
	 * 真正用于上传的方法
	 * 
	 * @param fileName
	 * @param newName
	 * @param path
	 * @throws Exception
	 */
	private void upload(String fileName, String newName, String path)
			throws Exception 
		//String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
		String savefilename = fileName;
		File file_in = new File(savefilename);// 打开本地待长传的文件
		if (!file_in.exists()) 
			throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");
		
		if (file_in.isDirectory()) 
			if (!isDirExist(newName)) 
				createDir(newName);
			
			ftpClient.cd(newName);
			File sourceFile[] = file_in.listFiles();
			for (int i = 0; i < sourceFile.length; i++) 
				if (!sourceFile[i].exists()) 
					continue;
				
				if (sourceFile[i].isDirectory()) 
					this.upload(sourceFile[i].getPath(),
							sourceFile[i].getName(), path + "/" + newName);
				 else 
					this.uploadFile(sourceFile[i].getPath(),
							sourceFile[i].getName());
				
			
		 else 
			uploadFile(file_in.getPath(), newName);
		
		ftpClient.cd(path);
	

	/**
	 * upload 上传文件
	 * 
	 * @param filename
	 *            要上传的文件名
	 * @param newname
	 *            上传后的新文件名
	 * @return -1 文件不存在 >=0 成功上传,返回文件的大小
	 * @throws Exception
	 */
	public long uploadFile(String filename, String newname) throws Exception 
		long result = 0;
		TelnetOutputStream os = null;
		FileInputStream is = null;
		try 
			java.io.File file_in = new java.io.File(filename);
			if (!file_in.exists())
				return -1;
			os = ftpClient.put(newname);
			result = file_in.length();
			is = new FileInputStream(file_in);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) 
				os.write(bytes, 0, c);
				trans = trans + c;			
			
		 finally 
			if (is != null) 
				is.close();
			
			if (os != null) 
				os.close();
			
		
		return result;
	

	/**
	 * 从ftp下载文件到本地
	 * 
	 * @param filename
	 *            服务器上的文件名
	 * @param newfilename
	 *            本地生成的文件名
	 * @return
	 * @throws Exception
	 */
	public long downloadFile(String filename, String newfilename) 
		long result = 0;
		TelnetInputStream is = null;
		FileOutputStream os = null;
		try 
			is = ftpClient.get(filename);
			java.io.File outfile = new java.io.File(newfilename);
			os = new FileOutputStream(outfile);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) 
				os.write(bytes, 0, c);
				result = result + c;
			
		 catch (IOException e) 
			e.printStackTrace();
		 finally 
			try 
				if (is != null) 
					is.close();
				
				if (os != null) 
					os.close();
				
			 catch (IOException e) 
				e.printStackTrace();
			
		
		return result;
	

	/**
	 * 取得相对于当前连接目录的某个目录下所有文件列表
	 * 
	 * @param path
	 * @return
	 */
	public List getFileList(String path) 
		List list = new ArrayList();
		DataInputStream dis;
		try 
			dis = new DataInputStream(ftpClient.nameList(this.path + path));
			String filename = "";
			while ((filename = dis.readLine()) != null) 
				list.add(filename);
			
		 catch (IOException e) 
			e.printStackTrace();
		
		return list;
	

	public static void main(String[] args) 
		FtpUtils ftp = new FtpUtils("192.168.1.100", 8833, "ScumVirus",
				"123456");
		ftp.connectServer();
		boolean result = ftp.upload("E:/11game", "");
		System.out.println(result ? "上传成功!" : "上传失败!");
		ftp.closeServer();
		/**
		 * FTP远程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR
		 * REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU
		 * AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR
		 * NLST MKD XPWD MDTM PROT
		 * 在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\\r\\n
		 * ftpclient.sendServer("XMKD /test/bb\\r\\n"); //执行服务器上的FTP命令
		 * ftpclient.readServerResponse一定要在sendServer后调用
		 * nameList("/test")获取指目录下的文件列表 XMKD建立目录,当目录存在的情况下再次创建目录时报错 XRMD删除目录
		 * DELE删除文件
		 */
	


刷新进度条线程:

//刷新进度条线程
class ProgressThread extends Thread 
	private JProgressBar progressBar;

	public ProgressThread(JProgressBar progressBar) 
		this.progressBar = progressBar;
	

	public void run() 
		while (flag) 
			int k = (int) (FtpUtils.trans * 100 / FtpUtils.totalSize);
			progress.setValue(k);
			try 
				Thread.sleep(1000);
			 catch (InterruptedException e) 
				e.printStackTrace();
			
		
	
界面效果图

附上源码:点击下载




javaftp上传文件(进度条显示进度)

<spanstyle="font-family:Arial,Helvetica,sans-serif;background-color:rgb(255,255,255);">java实现FTP上传有2种方式,一种是org.apache.commons.net.ftp.FTPClient这个jar包,一种是sun.net.ftp.Ftp 查看详情

如何在ajax文件上传中显示进度条

】如何在ajax文件上传中显示进度条【英文标题】:Howtoshowprogressbarinajaxfileupload【发布时间】:2013-01-2605:22:52【问题描述】:我的代码发布了ajax请求,但没有显示进度条。请帮助更正代码以显示工作进度条。$(document).ready(function()... 查看详情

使用引导进度条以模态显示上传进度

】使用引导进度条以模态显示上传进度【英文标题】:DisplayUploadProgressinModalwithBootstrapProgressBar【发布时间】:2015-04-2003:01:02【问题描述】:我正在构建一个c#MVC应用程序,它显示一个表单并允许用户上传一些文件。当用户点击提... 查看详情

文件上传和进度条

】文件上传和进度条【英文标题】:Fileuploadandprogessbar【发布时间】:2013-01-2114:01:05【问题描述】:我想在上传文件时根据读取的文件数量显示进度条。我们如何使用JS和Servlet来实现这一点我知道上传我可以使用apachecommonslib,但... 查看详情

struts2文件上传进度条显示

参考成功博客:http://blog.sina.com.cn/s/blog_bca9d7e80101bkko.html待测试博客:http://blog.csdn.net/z69183787/article/details/52536255Struts2文件上传进度条显示 查看详情

如何在 Django 中上传文件并显示进度条?

】如何在Django中上传文件并显示进度条?【英文标题】:HowtouploadafileandshowprogressbarinDjango?【发布时间】:2011-07-0117:28:33【问题描述】:我已经编写了在Django中上传文件的代码,如下所示:defupload(request):ifrequest.method==\'POST\':form=Up... 查看详情

java多文件上传显示进度条

用java或者js实现对多文件上传,并显示进度条,可以只显示总进度。手上有类似代码的朋友联系我,扣-15080818,跪求!使用  apachefileupload  ,springMVC  jquery1.6x,bootstrap 实现一个带进度条的多文件上传,由于fileupload的局限,暂... 查看详情

如何通过 ASP.NET MVC 上传文件并显示进度条?

】如何通过ASP.NETMVC上传文件并显示进度条?【英文标题】:HowcanIuploadafileviaASP.NETMVCandshowaprogressbar?【发布时间】:2010-11-0122:56:22【问题描述】:我希望允许用户在我的ASP.NETMVC应用程序中浏览文件并将其上传到服务器。如果可能... 查看详情

uploadifive.js怎么去掉进度条

参考技术AUploadify中上传完毕会默认保留进度条并显示100%,前提设置removeCompleted为false,而UploadiFive中上传完毕后进度条自动消失 参考技术BUploadify中上传完毕会默认保留进度条并显示100%,前提设置removeCompleted为false,而UploadiFive... 查看详情

jquery上传文件显示进度条(代码片段)

<!DOCTYPEhtml><html><head><metacharset="UTF-8"><scriptsrc="../js/jquery.js"></script></head><body><h2>HTML5异步上传文件,带进度条(jQuery)</h2><formm 查看详情

Dropzone.js 上传进度条不显示

】Dropzone.js上传进度条不显示【英文标题】:Dropzone.jsuploadprogressbarnotshowing【发布时间】:2014-05-2003:02:57【问题描述】:我正在使用Dropzone.js进行文件上传,它运行良好,只是没有出现进度条。没有错误。我在网站的前端使用Bootst... 查看详情

MVC 文件上传的引导进度条

】MVC文件上传的引导进度条【英文标题】:BootstrapProgressBarforMVCFileUpload【发布时间】:2014-08-2402:38:06【问题描述】:有没有一种简单的方法可以在文件加载时显示阻塞的Bootstrap进度条?上传文件时,进度会显示在chrome的状态栏中... 查看详情

vue多文件上传进度条进度不更新问题

...完全没人能回答。谢谢这篇文章 最近在做一个多图片上传的组件,需求是做到多文件依次上传,并显示上传进度条。逻辑部分实现了以后,在更新进度条视图的时候出现一点问题:动态计算生产的进度progress属性不会自动更... 查看详情

vc下载文件显示进度条

VC下载文件显示进度条 逗比汪星人2009-09-18上传 byKomahttp://blog.csd.net/wangningyuhttp://download.csdn.net/detail/wangningyu/1674247 查看详情

asp.net上传大文件带进度条swfupload

Asp.Net基于swfupload上传大文件带进度条百分比显示,漂亮大气上档次,大文件无压力,先看效果一、上传效果图1、上传前界面:图片不喜欢可以自己换2、上传中界面:百分比显示 3、上传后返回文件地址,我测试呢所以乱写... 查看详情

异步上传,显示进度条

服务端代码[HttpPost]publicActionResultDoLoad(HttpPostedFileBaseupimage,stringtest){stringfilePhysicalPath=Server.MapPath("~/Upload/"+test);if(System.IO.File.Exists(filePhysicalPath)){System.IO.Streamupload 查看详情

通过后处理上传进度

】通过后处理上传进度【英文标题】:uploadprogresswithpostprocessing【发布时间】:2015-02-2517:24:30【问题描述】:我有一个上传表单,用户可以在其中上传文件。上传完成后,对文件进行后处理,有时上传完成后处理需要10-15秒。上... 查看详情

java上传excel文件,如何实现进度条显示?

比如,Excel有100条数据,上传20条时显示20%,并且支持后面带“×”按钮,以结束上传。有知道留下联系方式,可以追加分。参考技术A您好,1、开发简单,由于要定时起一个HTTP连接去获得进度信息,因此,发生的连接请求也增多... 查看详情