ftp上传

1.上传工具类
package com.kingdee.youshang.platform.app.common.util;

import com.kingdee.youshang.platform.app.manage.action.UploadFormBean;
import java.io.*;
import java.util.*;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.*;
import org.apache.log4j.Logger;


 
 
public class FtpUtil
{

	private static Logger LOG = Logger.getLogger(com/kingdee/youshang/platform/app/common/util/FtpUtil);
	private String localBasePath;
	private String remoteBasePath;
	private List allFile;
	private FTPClient ftpClient;

	public String getLocalBasePath()
	{
		return localBasePath;
	}

	public void setLocalBasePath(String localBasePath)
	{
		this.localBasePath = localBasePath;
	}

	public String getRemoteBasePath()
	{
		return remoteBasePath;
	}

	public void setRemoteBasePath(String remoteBasePath)
	{
		this.remoteBasePath = remoteBasePath;
	}

	public FtpUtil()
	{
		localBasePath = "";
		remoteBasePath = "";
		allFile = new ArrayList();
		ftpClient = new FTPClient();
		ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
	}

	public boolean connect(String hostname, int port, String username, String password)
		throws IOException
	{
		ftpClient.connect(hostname, port);
		ftpClient.setControlEncoding("UTF-8");
		if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.login(username, password))
		{
			return true;
		} else
		{
			disconnect();
			return false;
		}
	}

	public DownloadStatus download1(String remote, String local)
		throws IOException
	{
		ftpClient.enterLocalPassiveMode();
		ftpClient.setFileType(2);
		ftpClient.setControlEncoding("UTF-8");
		FTPFile files[] = ftpClient.listFiles(new String(remote.getBytes("UTF-8")));
		if (files.length < 1)
		{
			LOG.debug("远程文件不存在");
			return DownloadStatus.Remote_File_Noexist;
		}
		long lRemoteSize = files[0].getSize();
		File f = new File(local);
		OutputStream out = new FileOutputStream(f);
		InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("UTF-8")));
		byte bytes[] = new byte[8192];
		long localSize = 0L;
		int c;
		while ((c = in.read(bytes)) != -1) 
		{
			out.write(bytes, 0, c);
			localSize += c;
			LOG.debug((new StringBuilder()).append("下载进度:").append(localSize).append("/").append(lRemoteSize).toString());
		}
		in.close();
		out.close();
		boolean upNewStatus = ftpClient.completePendingCommand();
		DownloadStatus result;
		if (upNewStatus)
			result = DownloadStatus.Download_New_Success;
		else
			result = DownloadStatus.Download_New_Failed;
		return result;
	}

	public List getFtpFileNames(String remoteDir)
		throws Exception
	{
		List fileList = new ArrayList();
		ftpClient.enterLocalPassiveMode();
		ftpClient.setFileType(2);
		ftpClient.setControlEncoding("UTF-8");
		ftpClient.changeWorkingDirectory((new StringBuilder()).append(remoteBasePath).append("/").toString());
		FTPFile files[] = ftpClient.listFiles(new String(remoteDir.getBytes("UTF-8")));
		UploadFormBean bean = null;
		if (files.length > 0)
		{
			FTPFile arr$[] = files;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i+)
			{
				FTPFile rfile = arr$[i$];
				if (rfile.isFile())
				{
					bean = new UploadFormBean();
					bean.setFilename(rfile.getName());
					bean.setIsFile("Y");
					fileList.add(bean);
				} else
				{
					bean = new UploadFormBean();
					bean.setFilename(rfile.getName());
					bean.setIsFile("N");
					bean.setFileDir((new StringBuilder()).append(remoteDir).append(rfile.getName()).append("/").toString());
					fileList.add(bean);
				}
			}

		}
		return fileList;
	}

	public void getAllFileName(String localDir)
	{
		UploadStatus result = UploadStatus.Upload_New_File_Success;
		localDir = localDir.replace('/', File.separatorChar);
		File localFile = new File(localDir);
		if (localFile.isDirectory())
		{
			File fileList[] = localFile.listFiles();
			File arr$[] = fileList;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i+)
			{
				File file = arr$[i$];
				if (file.isFile())
				{
					String path = file.getPath();
					path = path.replace('/', File.separatorChar);
					String subpath = path.substring(path.indexOf(localBasePath) + localBasePath.length());
					LOG.debug((new StringBuilder()).append("==subPath:").append(subpath).toString());
					allFile.add(subpath);
					continue;
				}
				if (file.isDirectory())
				{
					String path = file.getPath();
					path = path.replace('/', File.separatorChar);
					getAllFileName(path);
				}
			}

		}
	}

	public UploadStatus upload(String local, String remote)
		throws IOException
	{
		ftpClient.enterLocalPassiveMode();
		ftpClient.setFileType(2);
		ftpClient.setControlEncoding("UTF-8");
		String remoteFileName = remote;
		if (remote.contains("/"))
		{
			remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
			if (CreateDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail)
				return UploadStatus.Create_Directory_Fail;
		}
		UploadStatus result = uploadFile(remoteFileName, new File(local), ftpClient);
		return result;
	}

	public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient)
		throws IOException
	{
		ftpClient.changeWorkingDirectory("/");
		UploadStatus status = UploadStatus.Create_Directory_Success;
		String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
		if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(new String(directory.getBytes("UTF-8"))))
		{
			int start = 0;
			int end = 0;
			if (directory.startsWith("/"))
				start = 1;
			else
				start = 0;
			end = directory.indexOf("/", start);
			do
			{
				String subDirectory = new String(remote.substring(start, end).getBytes("UTF-8"));
				if (!ftpClient.changeWorkingDirectory(subDirectory))
					if (ftpClient.makeDirectory(subDirectory))
					{
						ftpClient.changeWorkingDirectory(subDirectory);
					} else
					{
						LOG.debug("创建目录失败");
						return UploadStatus.Create_Directory_Fail;
					}
				start = end + 1;
				end = directory.indexOf("/", start);
			} while (end > start);
		} else
		if (directory.equalsIgnoreCase("/"))
			ftpClient.changeWorkingDirectory("/");
		return status;
	}

	public UploadStatus uploadFile(String remoteFile, File localFile, FTPClient ftpClient)
		throws IOException
	{
		ftpClient.deleteFile(remoteFile);
		long step = localFile.length();
		if (localFile.length() > 8192L)
			step = localFile.length() / 8192L;
		long process = 0L;
		long localreadbytes = 0L;
		RandomAccessFile raf = new RandomAccessFile(localFile, "r");
		OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("UTF-8")));
		byte bytes[] = new byte[8192];
		do
		{
			int c;
			if ((c = raf.read(bytes)) == -1)
				break;
			out.write(bytes, 0, c);
			localreadbytes += c;
			if (localreadbytes / step != process)
			{
				process = localreadbytes / step;
				LOG.debug((new StringBuilder()).append("上传进度:").append(process).toString());
			}
		} while (true);
		out.flush();
		raf.close();
		out.close();
		boolean result = ftpClient.completePendingCommand();
		UploadStatus status = result ? UploadStatus.Upload_New_File_Success : UploadStatus.Upload_New_File_Failed;
		return status;
	}

	public void uploadPackage(String localDir, String remoteDir)
		throws IOException
	{
		setLocalBasePath(localDir);
		getAllFileName(localDir);
		String name;
		String localname;
		for (Iterator i$ = allFile.iterator(); i$.hasNext(); upload(localname, name))
		{
			name = (String)i$.next();
			localname = (new StringBuilder()).append(localBasePath).append(name).toString();
			localname = localname.replace('/', File.separatorChar);
			localname = localname.replace("\\", "/");
			name = (new StringBuilder()).append(remoteDir).append(name).toString().replace('/', File.separatorChar);
			name = name.replace("\\", "/");
			name = name.replace("//", "/");
			LOG.debug((new StringBuilder()).append("---------localname=").append(localname).toString());
			LOG.debug((new StringBuilder()).append("---------name=").append(name).toString());
		}

	}

	public void disconnect()
		throws IOException
	{
		if (ftpClient.isConnected())
			ftpClient.disconnect();
	}

	public static void main(String args[])
		throws Exception
	{
		FtpUtil myFtp = new FtpUtil();
		InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("youshang-app-ftp.properties");
		Properties properties = new Properties();
		try
		{
			properties.load(input);
			myFtp.connect(properties.getProperty("hostname"), Integer.parseInt(properties.getProperty("post")), properties.getProperty("username"), properties.getProperty("password"));
			List fileList = myFtp.getFtpFileNames("KISAppPlatForm/");
			UploadFormBean bean;
			for (Iterator i$ = fileList.iterator(); i$.hasNext(); System.out.println((new StringBuilder()).append(bean.getFilename()).append(":").append(bean.getIsFile()).toString()))
				bean = (UploadFormBean)i$.next();

			myFtp.disconnect();
		}
		catch (IOException e)
		{
			System.out.println((new StringBuilder()).append("连接FTP出错:").append(e.getMessage()).toString());
		}
	}

}

2.action  

	private ActionForward uploadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	{
		UploadFormBean fileForm = (UploadFormBean)form;
		String remotePath = fileForm.getFilePath();
		request.setAttribute("filePath", remotePath);
		Long categoryId = fileForm.getCid();
		String appName = fileForm.getAppName();
		request.setAttribute("appName", appName);
		request.setAttribute("cid", categoryId);
		FormFile formFile = fileForm.getFileToUpload();
		System.out.println(formFile.getFileName());
		String path = "";
		String filename = "";
		path = request.getSession().getServletContext().getRealPath("/appUpload/");
		filename = request.getSession().getServletContext().getRealPath((new StringBuilder()).append("/appUpload/").append(formFile.getFileName()).toString());
		try
		{
			deleteFiles(path);
			InputStream ins = formFile.getInputStream();
			File zipFile = new File(filename);
			FileOutputStream fout = new FileOutputStream(zipFile);
			byte buf[] = new byte[8192];
			for (int count = 0; (count = ins.read(buf)) > 0;)
				fout.write(buf, 0, count);

			fout.close();
			unzip(filename, path);
			File zipfile = new File(filename);
			if (zipfile.exists() && zipfile.isFile())
				zipfile.delete();
			uploadToFtp((new StringBuilder()).append(path).append("/").toString(), remotePath);
			request.setAttribute("msg", "上传成功");
			deleteFiles(path);
			String currentDir = ParamUtils.getString(request, "currentDir", remotePath);
			List fileList = getFtpFileNames(currentDir);
			if (!currentDir.equals(remotePath))
			{
				if (currentDir.contains("/"))
				{
					String tmpDir = currentDir.substring(0, currentDir.lastIndexOf("/"));
					if (tmpDir.contains("/"))
					{
						String preDir = tmpDir.substring(0, tmpDir.lastIndexOf("/"));
						request.setAttribute("preDir", (new StringBuilder()).append(preDir).append("/").toString());
					}
				}
			} else
			{
				request.setAttribute("preDir", remotePath);
			}
			request.setAttribute("fileList", fileList);
		}
		catch (Exception e)
		{
			LOG.debug(e);
			if (e.getMessage() != null)
				request.setAttribute("msg", (new StringBuilder()).append("上传失败:").append(e.getMessage()).toString());
			else
				request.setAttribute("msg", "上传失败!");
		}
		return mapping.findForward("toupload");
	}

	private ActionForward queryFtpFiles(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		throws Exception
	{
		try
		{
			String filePath = ParamUtils.getString(request, "filePath");
			Long categoryId = Long.valueOf(ParamUtils.getLong(request, "cid", 0L));
			String appName = ParamUtils.getString(request, "appName");
			request.setAttribute("filePath", filePath);
			request.setAttribute("cid", categoryId);
			request.setAttribute("appName", appName);
			String currentDir = ParamUtils.getString(request, "currentDir", filePath);
			List fileList = getFtpFileNames(currentDir);
			if (!currentDir.equals(filePath))
			{
				if (currentDir.contains("/"))
				{
					String tmpDir = currentDir.substring(0, currentDir.lastIndexOf("/"));
					if (tmpDir.contains("/"))
					{
						String preDir = tmpDir.substring(0, tmpDir.lastIndexOf("/"));
						request.setAttribute("preDir", (new StringBuilder()).append(preDir).append("/").toString());
					}
				}
			} else
			{
				request.setAttribute("preDir", filePath);
			}
			request.setAttribute("fileList", fileList);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			LOG.debug(e);
		}
		return mapping.findForward("toupload");
	}

	private List getFtpFileNames(String remotePath)
	{
		List fileList = new ArrayList();
		FtpUtil ftpUtil = new FtpUtil();
		KDConfig kdConfig = (KDConfig)Env.getBean("reportConfig");
		try
		{
			ftpUtil.connect(kdConfig.getProperty("ftp.hostname"), Integer.parseInt(kdConfig.getProperty("ftp.post")), kdConfig.getProperty("ftp.username"), kdConfig.getProperty("ftp.password"));
			ftpUtil.setRemoteBasePath(kdConfig.getProperty("ftp.subpath"));
			fileList = ftpUtil.getFtpFileNames(remotePath);
			ftpUtil.disconnect();
		}
		catch (Exception e)
		{
			LOG.debug(e);
		}
		return fileList;
	}

	public void unzip(String zipFile, String targetFolder)
		throws Exception
	{
		byte buf[] = new byte[8192];
		ZipFile zip = new ZipFile(zipFile);
		Enumeration enumeration = zip.entries();
		do
		{
			if (!enumeration.hasMoreElements())
				break;
			ZipEntry entry = (ZipEntry)enumeration.nextElement();
			File file = new File(targetFolder, entry.getName());
			String filePath = file.getAbsolutePath();
			if (entry.isDirectory())
			{
				if (!file.exists())
					file.mkdir();
			} else
			{
				InputStream zin = zip.getInputStream(entry);
				OutputStream fout = new FileOutputStream(filePath);
				do
				{
					int bytesRead = zin.read(buf);
					if (bytesRead == -1)
						break;
					fout.write(buf, 0, bytesRead);
				} while (true);
				fout.flush();
				fout.close();
			}
		} while (true);
		zip.close();
	}

	private File getRootFolder(ZipFile zip, String targetFolder)
	{
		File rootFolder = null;
		Enumeration enumeration = zip.entries();
		do
		{
			if (!enumeration.hasMoreElements())
				break;
			ZipEntry entry = (ZipEntry)enumeration.nextElement();
			File file = new File(targetFolder, entry.getName());
			if (!entry.isDirectory() || rootFolder != null)
				continue;
			rootFolder = file;
			break;
		} while (true);
		return rootFolder;
	}

	private void uploadToFtp(String localPath, String remotePath)
		throws Exception
	{
		FtpUtil ftpUtil = new FtpUtil();
		KDConfig kdConfig = (KDConfig)Env.getBean("reportConfig");
		ftpUtil.connect(kdConfig.getProperty("ftp.hostname"), Integer.parseInt(kdConfig.getProperty("ftp.post")), kdConfig.getProperty("ftp.username"), kdConfig.getProperty("ftp.password"));
		ftpUtil.uploadPackage(localPath, (new StringBuilder()).append(kdConfig.getProperty("ftp.subpath")).append("/").append(remotePath).toString());
		ftpUtil.disconnect();
	}

	private void deleteFiles(String filepath)
		throws IOException
	{
		File f = new File(filepath);
		if (f.exists() && f.isDirectory())
		{
			File delFile[] = f.listFiles();
			int i = f.listFiles().length;
			for (int j = 0; j < i; j++)
			{
				if (delFile[j].isDirectory())
					deleteFiles(delFile[j].getAbsolutePath());
				delFile[j].delete();
			}

		}
	}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FTP(文件传输协议)是一种用于在网络上传输文件的标准协议。它可以让用户通过FTP客户端将文件从一个位置上传到另一个位置,或者从一个位置下载到本地计算机。 FTP上传是将文件从本地计算机上传到远程服务器的过程。首先,用户需要连接到FTP服务器,并使用正确的用户名和密码进行身份验证。一旦连接建立,用户可以使用FTP客户端在本地计算机上选择要上传的文件,然后将其传输到服务器上的目标位置。上传过程中,需要确保网络连接稳定,并且上传的文件在传输过程中不会被损坏。 FTP下载是将文件从远程服务器下载到本地计算机的过程。同样地,用户需要连接到FTP服务器,并进行身份验证。一旦连接建立,用户可以使用FTP客户端浏览服务器上可用的文件,并选择要下载的文件。下载过程中,文件将从服务器传输到本地计算机的指定目录中。 FTP上传和下载可以用于许多不同的场景。例如,网站管理员可以使用FTP上传网站文件到服务器上,以便在互联网上进行访问。用户也可以使用FTP下载软件、音频、视频等文件到自己的计算机上。此外,FTP还可以用于公司内部文件共享,团队成员可以通过FTP将文件传输给其他成员。 总而言之,FTP上传和下载是一种可靠的文件传输方法,允许用户在本地计算机和远程服务器之间传输文件。它在很多领域都有广泛的应用,为用户提供了便利和灵活性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值