设为首页 收藏本站
查看: 1305|回复: 0

[经验分享] 跨域上传图片之FTP上传

[复制链接]

尚未签到

发表于 2016-6-9 07:54:17 | 显示全部楼层 |阅读模式
  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 portFTP端口,如21
* @param userFTP登录用户名,如:ADMIN
* @param passwordFTP登录密码,如:111111
* @param pathFTP上传路径,如: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 portFTP端口,如21
* @param userFTP登录用户名,如:ADMIN
* @param passwordFTP登录密码,如:111111
* @param pathFTP上传路径,如: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>
  
  其他的就不用多说了,代码中的注释说的很清楚,大家可以自己看下

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228008-1-1.html 上篇帖子: HTTP,FTP断点续传(上传,下载) 下篇帖子: FTP服务器的工作方式
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表