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();
			}

		}
	}
 
  
 
 

你可能感兴趣的:(java)