您的位置:首页 > 编程语言 > Java开发

struts2 上传文件 FtpClient ftp操作

2010-07-09 14:10 323 查看
网上很多介绍struts2 上传文件的例子,但很多都忘记了说明要加上拦截器fileUploadStack,否则得到的file将会是空的,以下是项目中用到的代码,同时涉及到ftp操作

Action类

/**
* ViewAction.java
* com.sword.actions
*
* Function: TODO
*
*   ver     date      		author
* ──────────────────────────────────
*   		 2010-7-1 		lidl
*
* Copyright (c) 2010, TNT All Rights Reserved.
*/
package com.sword.actions;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import com.opensymphony.xwork2.ActionSupport;
import com.sword.util.FtpUtil;
import com.webservice.SingleMap;
/**
* ClassName:ViewAction
* Function: TODO ADD FUNCTION
* Reason:	 TODO ADD REASON
*
* @author   lidl
* @version
* @since    Ver 1.1
* @Date	 2010-7-1		下午05:54:31
*
* @see
*/
public class ViewAction extends ActionSupport{
private int validateNum;
private File attachment;
private String attachmentFileName;
private String attachmentContentType;
@Action(interceptorRefs=@InterceptorRef("fileUploadStack"))
public String execute(){
SingleMap map = SingleMap.getInstance();
int num_int=((Integer)map.map.get("login")).intValue();
System.out.println("num_int:"+num_int+",validateNum:"+validateNum+"->"+(num_int==validateNum));
System.out.println("size:" + map.map.size());
map.map.remove("login");
if(num_int==validateNum){
System.out.println(attachment == null);
String targetDirectory = ServletActionContext.getServletContext()
.getRealPath("/temp");
String targetFileName = generateFileName(attachmentFileName);
File target = new File(targetDirectory, targetFileName);
targetDirectory+="/"+targetFileName;
try {
FileUtils.copyFile(attachment, target);
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println(targetDirectory);
FtpUtil ftp=new FtpUtil();
try {
ftp.connectServer("192.168.32.130", "lidl", "aall", "/ftp");
System.out.println("filesize:"
+ ftp.upload(targetDirectory) + "字节");
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();

} catch (Exception e) {

// TODO Auto-generated catch block
e.printStackTrace();

}finally{
try {
ftp.closeServer();
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();

}
}
}
return "success";
}else{
return "error";
}
}
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());

int random = new Random().nextInt(10000);

int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);

return formatDate + random + extension;
}
public int getValidateNum() {
return validateNum;
}
public void setValidateNum(int validateNum) {
this.validateNum = validateNum;
}
public File getAttachment() {
return attachment;
}
public void setAttachment(File attachment) {
this.attachment = attachment;
}
public String getAttachmentFileName() {
return attachmentFileName;
}
public void setAttachmentFileName(String attachmentFileName) {
this.attachmentFileName = attachmentFileName;
}
public String getAttachmentContentType() {
return attachmentContentType;
}
public void setAttachmentContentType(String attachmentContentType) {
this.attachmentContentType = attachmentContentType;
}

}


(文件上传 ,请在struts.xml里配上 <constant name="struts.multipart.saveDir" value="/tmp"/> 用来保存临时文件,同时为了 让系统清除临时文件 请在web.xml里配上 )

web.xml

<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
com.sword.actions.FilterDispetor
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


ftp 操作类

package com.sword.util;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class FtpUtil {

private FtpClient ftpClient;
/**
* connectServer 连接ftp服务器
*
* @throws java.io.IOException
* @param path
*            文件夹,空代表根目录
* @param password
*            密码
* @param user
*            登陆用户
* @param server
*            服务器地址
*/
public void connectServer(String server, String user, String password,
String path) throws IOException {
// server:FTP服务器的IP地址;user:登录FTP服务器的用户名
// password:登录FTP服务器的用户名的口令;path:FTP服务器上的路径
ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user, password);
// path是ftp服务下主目录的子目录
if (path.length() != 0)
ftpClient.cd(path);
// 用2进制上传、下载
ftpClient.binary();
}
/**
* upload 上传文件
*
* @throws java.lang.Exception
* @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
* @param newname
*            上传后的新文件名
* @param filename
*            上传的文件
*/
public long upload(String filename, String newname) throws Exception {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
if (file_in.length() == 0)
return -2;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* upload
*
* @throws java.lang.Exception
* @return
* @param filename
*/
public long upload(String filename) throws Exception {
String newname = "";
if (filename.indexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1);
} else {
newname = filename;
}
return upload(filename, newname);
}
/**
* download 从ftp下载文件到本地
*
* @throws java.lang.Exception
* @return
* @param newfilename
*            本地生成的文件名
* @param filename
*            服务器上的文件名
*/
public long download(String filename, String newfilename) throws Exception {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 取得某个目录下的所有文件列表
*
*/
public List getFileList(String path) {
List list = new ArrayList();
try {
DataInputStream dis = new DataInputStream(ftpClient.nameList(path));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* closeServer 断开与ftp服务器的链接
*
* @throws java.io.IOException
*/
public void closeServer() throws IOException {
if (ftpClient != null) {
ftpClient.closeServer();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: