网页控件 上传 文件

使用java程序直接读取硬盘文件上传和使用控件上传其实都是一样的,都是利用 common net 包的FTPClient 等类来上传文件,不同之处就在于如何在客户端获取文件。前一种方式是通过java的流对象来读取文件(InputStream iStream = new FileInputStream(fileName);),而后一种方式要通过程序解析来自客户端的request请求来得到文件流,前一种方式的代码可以参考上一篇《ftp 文件上传 文件损坏》,对于后一种方式,首先到apache上下载 commons fileupload 包,注意这个jar是基于commons-io 的,所以同时需要下载 commons-io 包:

http://commons.apache.org/downloads/download_fileupload.cgi

 

http://commons.apache.org/downloads/download_io.cgi

 

fileupload 的示例代码:

http://commons.apache.org/fileupload/using.html

 

 

操作类:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import com.util.common.JavaTypeConversionHelperInterface;

/** */
/**
 * 基于apache组织的commonNet开源组件实现ftp客户端<br>
 * 本程序运行依赖于一个config成员变量属性,其是一个属性(Properties)对象<br>
 * 系统要求这个config对象,必需有如下属性key:<br>
 * server(ftp服务器ip地址或域名)<br>
 * username(登录用户名)<br>
 * password(登录密码)<br>
 * 如下属性key是可选的:<br>
 * systemKey(ftp服务器的操作系统key,如window)<br>
 * serverLanguageCode(ftp服务器使用的语言,如zh)<br>
 * <br>
 * 本程序是线程安全,在每一个上传时都将创建ftp连接,上传结束后再关闭ftp连接<br>
 * 
 * 例子:<br>
 * InputStream localIn = new FileInputStream("c:\\计算机.txt");<br>
 * 
 * java.util.Properties config = new Properties();<br>
 * config.setProperty("server", "192.168.5.120");<br>
 * config.setProperty("username", "upload");<br>
 * config.setProperty("password", "upload");<br>
 * 
 * FtpClientCommonNetImpl client = new FtpClientCommonNetImpl();<br>
 * client.setConfig(config);<br>
 * client.upload(localIn, "/aaa/计算机.txt", true);<br>
 * 
 * 
 * @author zhangdb
 * 
 */
public class FtpClientCommonNetImpl {
	// ftp配置
	private Properties config;
	private JavaTypeConversionHelperInterface iJTH;
	public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
	public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
	/** */
	/**
	 * 连接到ftp服务器
	 * 
	 * @param server
	 * @param userName
	 * @param password
	 * @return
	 * @throws FtpException
	 */
	protected FTPClient connectFtpServer(String server, String userName,
			String password) throws Exception {
		// 创建ftp客户端对象
		FTPClient ftp = new FTPClient();
		try {
			ftp.setControlEncoding("UTF-8");
			ftp.configure(this.getFTPClientConfig());
			// 连接ftp服务器
			ftp.connect(server);
			// 登录
			ftp.login(userName, password);

			// 返回值
			int reply = ftp.getReplyCode();
			if ((!FTPReply.isPositiveCompletion(reply))) {
				ftp.disconnect();
				throw new Exception(" 登录ftp服务器失败,请检查server[ " + server
						+ " ]、username[ " + userName + " ]、password[ "
						+ password + " ]是否正确! ");
			}
			ftp.setFileType(BINARY_FILE_TYPE);
			return ftp;
		} catch (Exception ex) {
			throw new Exception(ex);
		}
	}

	/** */
	/**
	 * 关闭连接
	 * 
	 * @param ftp
	 */
	protected void disconnectFtpServer(FTPClient ftp) throws Exception {
		try {
			ftp.logout();
			ftp.disconnect();
		} catch (Exception ex) {
			throw new Exception(ex);
		}
	}

	/** */
	/**
	 * 上传
	 */
	public void upload(InputStream localIn, String remoteFilePath)
			throws Exception {
		String server = this.config.getProperty("server");
		String userName = this.config.getProperty("username");
		String password = this.config.getProperty("password");
		FTPClient ftp = this.connectFtpServer(server, userName, password);

		try {
			//boolean result = ftp.storeFile(this.enCodingRemoteFilePath(remoteFilePath), localIn);
			System.out.println(remoteFilePath);
			boolean result = ftp.storeFile(remoteFilePath, localIn);
			if (!result) {
				throw new Exception(" 文件上传失败! ");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex);
		} finally {
			this.disconnectFtpServer(ftp);
		}
	}

	/** */
	/**
	 * 上传结束以后关闭输入流
	 * 
	 * @param localIn
	 * @param remoteFilePath
	 * @param afterUploadCloseInputStream
	 * @throws FtpException
	 */
	public void upload(InputStream localIn, String remoteFilePath,
			boolean afterUploadCloseInputStream) throws Exception {
		try {
			// 上传
			this.upload(localIn, remoteFilePath);
		} finally {
			if (afterUploadCloseInputStream) {
				if (localIn != null) {
					try {
						localIn.close();
					} catch (Exception ex) {
						throw new Exception(ex);
					}
				}
			}
		}
	}

	/** */
	/**
	 * (www.iocblog.net 文章来源) 得到配置
	 * 
	 * @return
	 */
	protected FTPClientConfig getFTPClientConfig() {
		// 创建配置对象
		/*FTPClientConfig conf = new FTPClientConfig(this.config.getProperty(
				"systemKey", FTPClientConfig.SYST_NT));
		conf.setServerLanguageCode(this.config.getProperty(
				"serverLanguageCode", "zh"));*/
		
		
		
		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
		conf.setServerLanguageCode("zh");
		
		
		return conf;
	}
	
	/** */
	/**
	 * 远程文件路径编码(上传到ftp上的文件路径)
	 * 
	 * @param remoteFilePath
	 * @return
	 */
	protected String enCodingRemoteFilePath(String remoteFilePath)
			throws Exception {
		return iJTH.GBK2ISO(remoteFilePath);
	}

	public Properties getConfig() {
		return config;
	}

	public void setConfig(Properties config) {
		this.config = config;
	}

	/**
	 * @return the iJTH
	 */
	public JavaTypeConversionHelperInterface getIJTH() {
		return iJTH;
	}

	/**
	 * @param ijth
	 *            the iJTH to set
	 */
	public void setIJTH(JavaTypeConversionHelperInterface ijth) {
		iJTH = ijth;
	}

}

 servlet测试类import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.util.common.JavaTypeConversionHelper;
import com.util.ftp.FtpClientCommonNetImpl;

public class TestFTP extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public TestFTP() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// Check that we have a file upload request
		boolean isMultipart;
		try {
			isMultipart = ServletFileUpload.isMultipartContent(request);
			
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			//factory.setSizeThreshold(yourMaxMemorySize);
			//factory.setRepository(yourTempDirectory);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint
			//upload.setSizeMax(yourMaxRequestSize);

			// Parse the request
			List /* FileItem */ items = upload.parseRequest(request);
			
			// Process the uploaded items
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();

			    if (item.isFormField()) {
			        String name = item.getFieldName();
			        String value = item.getString();
			    } else {
			        String fieldName = item.getFieldName();
			        if(!fieldName.equalsIgnoreCase("defaults_0")) {
				        String fileName = item.getName();
				        String[] folders = fileName.split("\\"+File.separator);
				        String shortFileName = folders[folders.length-1];
				        String contentType = item.getContentType();
				        boolean isInMemory = item.isInMemory();
				        long sizeInBytes = item.getSize();
				        System.out.println(fieldName + "|"+fileName + "|" + shortFileName);
				        
						InputStream localIn = new FileInputStream(fileName);
						//工具类,转码用。
						JavaTypeConversionHelper jth = new JavaTypeConversionHelper();
						
						Properties config = new Properties();
						config.setProperty("server", "192.168.17.48");
						config.setProperty("username", "admin");
						config.setProperty("password", "123456");
						
						FtpClientCommonNetImpl client = new FtpClientCommonNetImpl();
						client.setConfig(config);
						client.setIJTH(jth);
						client.upload(localIn, shortFileName, true);
			        }

			    }
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

参考:

http://hejianke83.blog.163.com/blog/static/607651620088825458211/

 

http://commons.apache.org/fileupload/using.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值