【NCC】NCC 附件管理按钮开发,从ftp下载附件到文件服务器开发笔记

2 篇文章 0 订阅

1.附件管理按钮添加

参考即可

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
		<!-- 卡片界面 -->
		<bean class="nc.ui.pubapp.plugin.action.InsertActionInfo">
		<property name="actionContainer" ref="actionsOfCard" />
		<property name="actionType" value="notedit" />
		<property name="target" ref="printMenuAction" />
		<property name="pos" value="after"/>
		<property name="action" ref="accessoryShowAction" />
	    </bean> 
	    
       	<bean id="accessoryShowAction" class="nc.ui.so.pub.actions.SOManageDocumentAction">
		<property name="model" ref="manageAppModel" />
		</bean>
</beans>

2.ftp下载上传到文件服务器

package cn.ftp.util;
 
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pub.filesystem.IAttachManageConst;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.bs.pub.filesystem.UploadFileIsExistException;
import nc.impl.pub.filesystem.FileSpace;
import nc.impl.pub.filesystem.FileSpaceDAO;
import nc.impl.pub.filesystem.FileSystemImplement;
import nc.jdbc.framework.exception.DbException;
import nc.vo.pub.BusinessException;
import nc.vo.pub.filesystem.NCFileNode;
import nc.vo.pub.filesystem.NCFileVO;
import nccloud.framework.service.ServiceLocator;
import uap.pub.fs.client.FileStorageClient;
import uap.pub.fs.domain.basic.FileHeader;
 
/**
 * ftp工具类
 * @author lijj
 */
 
public class FtpUtil {
 
	private final static Log logger = LogFactory.getLog(FtpUtil.class);
	/** 本地字符编码 */
	private static String LOCAL_CHARSET = "GBK";
 
	// FTP协议里面,规定文件名编码为iso-8859-1
	private static String SERVER_CHARSET = "ISO-8859-1";
	
	/**
	 * 获取FTPClient对象
	 * 
	 * @param ftpHost
	 *            FTP主机服务器
	 * 
	 * @param ftpPassword
	 *            FTP 登录密码
	 * 
	 * @param ftpUserName
	 *            FTP登录用户名
	 * 
	 * @param ftpPort
	 *            FTP端口 默认为21
	 * 
	 * @return
	 */
	public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
			ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				logger.info("未连接到FTP,用户名或密码错误。");
				ftpClient.disconnect();
			} else {
				logger.info("FTP连接成功。");
			}
		} catch (SocketException e) {
			e.printStackTrace();
			logger.info("FTP的IP地址可能错误,请正确配置。");
		} catch (IOException e) {
			e.printStackTrace();
			logger.info("FTP的端口错误,请正确配置。");
		}
		return ftpClient;
	}
 
	/**
	 * 从FTP服务器下载文件
	 * 
	 * @param ftpHost FTP IP地址
	 * 
	 * @param ftpUserName FTP 用户名
	 * 
	 * @param ftpPassword FTP用户名密码
	 * 
	 * @param ftpPort FTP端口
	 * 
	 * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
	 * 
	 * @param localPath 下载到本地的位置 格式:H:/download
	 * 
	 * @param fileName 文件名称
	 * @throws BusinessException 
	 * @throws DbException 
	 */
	public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort,
			String ftpPath, String localPath, String fileName) throws BusinessException, DbException {
 
		FTPClient ftpClient = null;
 
		try {
			ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
			// 设置上传文件的类型为二进制类型
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
				LOCAL_CHARSET = "UTF-8";
			}
			ftpClient.setControlEncoding(LOCAL_CHARSET);
			ftpClient.enterLocalPassiveMode();// 设置被动模式
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
			// 上传文件
			//对中文文件名进行转码,否则中文名称的文件下载失败
			String fileNameTemp = new String(fileName.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
			String newfilepath = new String(ftpPath.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
//			ftpPath.getBytes("UTF-8"),"ISO-8859-1"
			String newpath = new String(ftpPath);
			boolean flag = ftpClient.changeWorkingDirectory(newfilepath);
			long fileLength = 0;
			FTPFile[] files = ftpClient.listFiles();
			for(FTPFile file:files) {
				if(file.getName().equals(fileName)) {
					fileLength = file.getSize();
					System.out.println(fileLength);
				}
			}
			
			InputStream retrieveFileStream = ftpClient.retrieveFileStream(fileNameTemp);
 
			// 第一种方式下载文件(推荐)
//			  File localFile = new File(localPath + File.separatorChar + fileName);
//			  OutputStream os = new FileOutputStream(localFile);
//			  ftpClient.retrieveFile(fileName, os); os.close();
			
			
			 //String parentpath = "1001A210000000000UPK";
			 String parentpath = "1001A110000000000OWX";
			 String creator="1001A210000000008QTG";
			
			
			
			// long fileLength =  retrieveFileStream.available();
			 

			 FileHeader fileHeader = FileStorageClient.getInstance().uploadFile(IAttachManageConst.RIAMoudleID, fileName, retrieveFileStream, false, new uap.pub.fs.domain.ext.IFileStorageExt[0]);
			 NCFileNode node = null;
			 if (fileHeader != null) {
			        String pk_doc = fileHeader.getPath();
			        NCFileVO attach = new NCFileVO();
			        attach.setPath(fileName);
			        attach.setCreator(creator);
			        attach.setIsdoc("z");
			        attach.setFileLen(fileLength);
			        attach.setPk_doc(pk_doc);
			        
			        String dsname = InvocationInfoProxy.getInstance()
			        		.getUserDataSource();
			        FileSpaceDAO dao = new FileSpaceDAO(dsname);
			        
			        String fullPath = parentpath + "/" + fileName;
			        
			        if(dao.isExist(fullPath)) {
			        	String [] fullPathArray = {fullPath};
			        	deleteNCFileNodes(fullPathArray);
			        	 System.out.println("看看有没有传过");
			        	 
			        	 
			        	 
			        	 
			        	 
			        }
			        
			        
			        
			        node = createCloudFileNode(parentpath, creator, attach);
			      } 
			 
			 
//			// 第二种方式下载:将输入流转成字节,再生成文件,这种方式方便将字节数组直接返回给前台jsp页面
			//byte[] input2byte = input2byte(retrieveFileStream);
			//byte2File(input2byte, localPath, fileName);
			 System.out.println(12312);
			
			if(null != retrieveFileStream){
				retrieveFileStream.close();
			}
		} catch (FileNotFoundException e) {
			logger.error("没有找到" + ftpPath + "文件");
			e.printStackTrace();
		} catch (SocketException e) {
			logger.error("连接FTP失败.");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("文件读取错误。");
			e.printStackTrace();
		} finally {
			
			if (ftpClient.isConnected()) {
				try {
					//退出登录
					ftpClient.logout();
					//关闭连接
					ftpClient.disconnect(); 
				} catch (IOException e) {
				}
			}
		}
	}
	
	
	public static void deleteNCFileNodes(String[] nodePaths) throws BusinessException {
	    String dsName = InvocationInfoProxy.getInstance().getUserDataSource();
	    FileSpace fileSpace = new FileSpace(dsName);
	    try {
	      fileSpace.deleteNCFileNodes(nodePaths);
	    } catch (Exception e) {
	      Logger.error(e.getMessage(), e);
	      throw new BusinessException(e.getMessage(), e);
	    } 
	  }
	
	
	public static NCFileNode createCloudFileNode(String parentPath, String creator, NCFileVO filevo) throws BusinessException {
	    String dsName = InvocationInfoProxy.getInstance().getUserDataSource();
	    FileSpace fileSpace = new FileSpace(dsName);
	    NCFileNode node = null;
	    try {
	      node = fileSpace.createCloudFileNode(parentPath, creator, filevo);
	    } catch (UploadFileIsExistException e) {
	      Logger.error(e.getMessage(), e);
	      throw e;
	    } catch (Exception e) {
	      Logger.error(e.getMessage(), e);
	      throw new BusinessException(e.getMessage(), e);
	    } 
	    return node;
	  }
 
	/**
	 * Description: 向FTP服务器上传文件
	 * 
	 * @param host
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param basePath
	 *            FTP服务器基础目录
	 * @param filePath
	 *            FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
	 * @param filename
	 *            上传到FTP服务器上的文件名
	 * @param input
	 *            输入流
	 * @return 成功返回true,否则返回false
	 */
	public static boolean uploadFile(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword,
			String basePath, String filePath, String filename, InputStream input) {
		boolean result = false;
		FTPClient ftpClient = null;
		try {
			int reply;
			ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
			reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				return result;
			}
			// 切换到上传目录
			if (!ftpClient.changeWorkingDirectory(basePath + filePath)) {
				// 如果目录不存在创建目录
				String[] dirs = filePath.split("/");
				String tempPath = basePath;
				for (String dir : dirs) {
					if (null == dir || "".equals(dir))
						continue;
					tempPath += "/" + dir;
					if (!ftpClient.changeWorkingDirectory(tempPath)) {
						if (!ftpClient.makeDirectory(tempPath)) {
							return result;
						} else {
							ftpClient.changeWorkingDirectory(tempPath);
						}
					}
				}
			}
			// 设置上传文件的类型为二进制类型
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
				LOCAL_CHARSET = "UTF-8";
			}
			ftpClient.setControlEncoding(LOCAL_CHARSET);
			ftpClient.enterLocalPassiveMode();// 设置被动模式
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
			// 上传文件
			filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
			if (!ftpClient.storeFile(filename, input)) {
				return result;
			}
			
			if(null != input){
				input.close();
			}
			
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					//退出登录
					ftpClient.logout();
					//关闭连接
					ftpClient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return result;
	}
 
	/**
	 * 删除文件 未测试
	 * 
	 * @param hostname
	 *            FTP服务器地址
	 * @param port
	 *            FTP服务器端口号
	 * @param username
	 *            FTP登录帐号
	 * @param password
	 *            FTP登录密码
	 * @param pathname
	 *            FTP服务器保存目录
	 * @param filename
	 *            要删除的文件名称
	 * @return
	 */
	public static boolean deleteFile(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String pathname,
			String filename) {
		boolean flag = false;
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
			// 验证FTP服务器是否登录成功
			int replyCode = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				return flag;
			}
			// 切换FTP目录
			ftpClient.changeWorkingDirectory(pathname);
			// 设置上传文件的类型为二进制类型
			if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
				LOCAL_CHARSET = "UTF-8";
			}
			ftpClient.setControlEncoding(LOCAL_CHARSET);
			ftpClient.enterLocalPassiveMode();// 设置被动模式
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
			//对中文名称进行转码
			filename = new String(filename.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
			ftpClient.dele(filename);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					//退出登录
					ftpClient.logout();
					//关闭连接
					ftpClient.disconnect();
				} catch (IOException e) {
				}
			}
		}
		return flag;
	}
 
	// 将字节数组转换为输入流
	public static final InputStream byte2Input(byte[] buf) {
		return new ByteArrayInputStream(buf);
	}
 
	// 将输入流转为byte[]
	public static final byte[] input2byte(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}
 
	// 将byte[]转为文件
	public static void byte2File(byte[] buf, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

3.测试代码

package cn.ftp.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;

import com.alibaba.fastjson.JSON;

import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.jdbc.framework.exception.DbException;
import nc.vo.pub.BusinessException;

public class FTPtest implements IHttpServletAdaptor {

	@Override
	public void doAction(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		try {
			//ftp服务器IP地址
			String ftpHost = "xxx.xx.xx.x";  
			//ftp服务器端口
			int ftpPort = 0000;  
			//ftp服务器用户名
			String ftpUserName = "aaa";
			//ftp服务器密码
			String ftpPassword = "asdasda";  
			//ftp服务器路径
			String ftpPath = "aa/"; 
      //本地路径
			String localPath = "D:/桌面/ftpdownload";  
			//文件名
			String fileName = "asdada-aaaa.zip";  
			
			
			//下载
			//将ftp根目录下的文件下载至E盘
			FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);  
      
			//上传
			//将E盘的文件上传至ftp根目录
			/*FileInputStream in=new FileInputStream(new File("e:/" + fileName)); 
			FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserName, ftpPassword, "ftpdir/", "/", fileName, in);*/
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("success", true);
			result.put("message", "成功");
			arg1.getOutputStream().write(JSON.toJSONString(result).getBytes("UTF-8"));
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			ExceptionUtils.wrapAndThrow(e);
		} 
        
	}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值