跨域上传图片之FTP上传

1、跟上一篇SWFUpload跨域请求处理的需求一样,都是将图片跨域上传到另一台服务器上,朋友介绍了另一种实现方法即FTP上传。

2、首先将commons-net-ftp-2.0.jar包准备一下

3、前端jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <link href="<%=basePath%>css/default.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
  <div id="content">
    <form action="ftpUpload.do" method="post" enctype="multipart/form-data">
		<table>
			<tr valign="top">
				<td>
					<input type="file" name="myFile"/>
					<input type="submit"/>
				</td>
			</tr>
		</table>
    </form>
    </div>
  </body>
</html>

 4、struts配置文件

<action name="ftpUpload" class="com.action.FTPAction" method="ftpUpload">
	<result name="success">/index_ftp.jsp</result>
	<result name="input">/index_ftp.jsp</result>
</action>

 5、action处理代码如下

package com.action;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;

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

import sw.common.util.ConfigDataInfo;

public class FTPAction extends BaseAction {
	/** */
	private static final long serialVersionUID = 1L;
	/**
	 * FtpClient对象 
	 */
	private FTPClient ftpClient;

	/**
	 * 缓冲的大小
	 */
	private String bufferSize;
	
	/**
	 * 文档的类型
	 */
	private String contentType;
	private File myFile;
	private String myFileFileName;
	private String myFileContentType;
	
	
	public String ftpUpload() {
		String server = ConfigDataInfo.getConfigValue("server");
		int port = Integer.parseInt(ConfigDataInfo.getConfigValue("port"));
		String user = ConfigDataInfo.getConfigValue("user");
		String password = ConfigDataInfo.getConfigValue("password");
		String path = ConfigDataInfo.getConfigValue("path");
		File file_in = myFile;
		this.ftpUploadFile(server, port, user, password, path, file_in);
		return SUCCESS;
	}
	
	/**
	 * ftp上传文件
	 * @param server FTP服务器地址,如192.168.0.111
	 * @param port	FTP端口,如21
	 * @param user	FTP登录用户名,如:ADMIN
	 * @param password	FTP登录密码,如:111111
	 * @param path	FTP上传路径,如:h:\ftp\
	 * @param file_in	上传文件 
	 */
	public String ftpUploadFile(String server,int port,String user,String password,String path,File file_in) {
		if (!file_in.isFile()) {
			// 是否文件,或找不到指定文件
			this.addActionError("customer.electroFile.errors.FileNotFound");
			return "";
		}else if(!fileSize(file_in)){
			//控制文件大小
			return "";
		}
		//文件名
		String file_inName="";
		//登录FTP服务器
		this.connectServer(server, port, user, password);
		//有出错信息
		if (hasActionErrors()) {
			return "";
		}
		try {
			if (path != null) {
				// 检查path最后有没有分隔符
				path = this.pathAddress(path);
				//新建路径
				// FTP转到PATH路径
				this.mkdir(server, port, user, password, path);
				ftpClient.changeWorkingDirectory(gbktoiso8859(path));
			} else {
				this.addActionError(getText("customer.electroFile.errors.ftpPath"));
				closeConnect();
				return "";
			}
			// 给文件名加上时间撮
			file_inName = this.getMyFileFileName();
			final int lastIndex = file_inName.lastIndexOf(".");
			
			file_inName = file_inName.substring(0, lastIndex) + "_"
					+ System.currentTimeMillis()
					+ file_inName.substring(lastIndex);

			FileInputStream fileIS=new FileInputStream(file_in);
			boolean flag=ftpClient.storeFile(gbktoiso8859(file_inName), fileIS);
			if (!flag) {
				closeConnect();
				this.addActionError("customer.electroFile.errors.FileUpload");
			}
		}catch(final FileNotFoundException fnfe){
			this.addActionError("customer.electroFile.errors.FileNotFound");
		} catch (final IOException ex) {
			this.addActionError(getText("customer.electroFile.errors.Connect"));
		}finally{
			//退出FTP服务器
			this.closeConnect();
		}
		return  file_inName;
	}
	
	/**
	 * 新建路径
	 * 
	 * @param server FTP服务器地址,如192.168.0.111
	 * @param port	FTP端口,如21
	 * @param user	FTP登录用户名,如:ADMIN
	 * @param password	FTP登录密码,如:111111
	 * @param path	FTP上传路径,如:h:\ftp\
	 * @param fileName 要删除的文件名
	 * @return
	 */
	public boolean mkdir(String server,int port,String user,String password,String path){

		this.connectServer(server, port, user, password);
		if (hasActionErrors()) {
			return false;
		}
		try {
			if (path!=null) {
				//检查path最后有没有分隔符
				path=this.pathAddress(path);
			}else {
				this.addActionError(getText("customer.electroFile.errors.ftpPath"));
				return false;
			}
			boolean flag=ftpClient.makeDirectory(gbktoiso8859(path));
			//错误也不给予提示
			return true;
			
		} catch (final IOException ex) {
			this.addActionError(getText("customer.electroFile.errors.mkdir"));
		}
		return false;
	}
	
	/**
	 * 登录ftp服务器
	 * 
	 * @param server
	 * @param port
	 * @param user
	 * @param password
	 * @
	 */
	private void connectServer(String server, int port, String user, String password) {

		if (ftpClient == null) {
			try {
				ftpClient=new FTPClient();
				//所有使用iso-8859-1做为通讯编码集
				//ftpClient.setControlEncoding("iso-8859-1");
				//ftpClient.configure(getFTPClientConfig());
	
				// 连接FTP服务器
				ftpClient.connect(server, port);
				// 登录FTP服务器
				if(!ftpClient.login(user, password)){
					this.addActionError(getText("customer.electroFile.errors.logonFTP"));
				}
				//状态
				int reply = ftpClient.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)) {
					 closeConnect();
					 this.addActionError(getText("customer.electroFile.errors.logonFTP"));
				}
				
				//  用被动模式传输
				ftpClient.enterLocalPassiveMode();
				// 将文件传输类型设置为二进制
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				//防止server超时断开
				//ftpClient.setDefaultTimeout(60000);
				//10超时
				ftpClient.setSoTimeout(10000);
			}catch(SocketException se){
				this.addActionError(getText("customer.electroFile.errors.logonFTP"));
				closeConnect();
			}catch (final IOException ex) {
				this.addActionError(getText("customer.electroFile.errors.logonFTP"));
				closeConnect();
			}
		}
	}
	
	/**
	 * 格式化文件路径
	 * @param path
	 * @return
	 */
	public String pathAddress(String path){
		
		if (path==null || path.length()<1) {
			return "";
		}
		String temp_path=path.substring(path.length()-1);
		if (!temp_path.equals("/") && !temp_path.equals("\\")) {
			temp_path=path+File.separator;
		}else{
			temp_path=path;
		}
		return temp_path;
		
	}
	
	/**
	 * 转码[GBK ->  ISO-8859-1]
	 *不同的平台需要不同的转码
	 * @param obj
	 * @return
	 */
	private static String gbktoiso8859(Object obj) {
		try {
			if (obj == null)
				return "";
			else
				return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 关闭连接
	 */
	private  void closeConnect() {
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (Exception e) {
			
		}
	}
	
	/**
	 * 控制文件的大小
	 * @param file_in
	 */
	private boolean fileSize(File file_in) {
		if (file_in == null || file_in.length() == 0) {
			addActionError(getText("customer.electroFile.errors.fileUnallowed"));
			return false;
		} else {
			if (file_in.length() > (1024 * 1024 * 5)){
				addActionError(getText("customer.electroFile.errors.fileTooLarge"));
				return false;
			}
		}
		return true;
	}
	
	public FTPClient getFtpClient() {
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public String getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(String bufferSize) {
		this.bufferSize = bufferSize;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public String getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}
	
}

6、还有一个参数的配置文件

<bean id="ConfigDataInfo" class="sw.common.util.ConfigDataInfo">
	<property name="configDataInfo">
		<map>
			<entry key="resourceServer" value="http://192.2.9.xxx:8090/gameshop" />
			<entry key="shopServer" value="http://192.2.9.xxx:8090/gameshop" />
			<entry key="server" value="192.2.11.xxx" />
			<entry key="user" value="user" />
			<entry key="password" value="pawd" />
			<entry key="port" value="21" />
			<entry key="path" value="" />
		</map>
	</property>
</bean>

 

其他的就不用多说了,代码中的注释说的很清楚,大家可以自己看下

你可能感兴趣的:(ftp)