我用jsp实现ftp上传功能,但是客户端不能往服务器端传上传文件,服务器端自己可以上传文件,代码如下:
package com.syh.struts.action;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class MainCtrlAction extends Action {
private FtpClient ftpClient;
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
try {
request.setCharacterEncoding("gbk");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
response.setCharacterEncoding("gbk");
try {
//连接ftp服务器
connectServer("127.0.0.1", "admin", "for720314","aa");
//上传文件;并返回上传文件的信息
request.setAttribute("inf", upload(request.getParameter("file")));
} catch (Exception e) {
System.out.println(e.toString());
request.setAttribute("inf", e.toString());
//request.getRequestDispatcher("view_inf.jsp").forward(request, response);
} finally {
if (ftpClient != null) {
try {
ftpClient.closeServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//request.getRequestDispatcher("view_inf.jsp").forward(request, response);
return mapping.findForward("cg");
}
private 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();
}
//上传文件;并返回上传文件的信息
private String upload(String filename) throws Exception {
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//"upftpfile"用ftp上传后的新文件名
String fn=filename.substring(filename.lastIndexOf("\")+1);
os = ftpClient.put(fn);
java.io.File file_in = new java.io.File(filename);
if (file_in.length()==0) {
return "上传文件为空!";
}
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 "上传文件成功!";
}
}
那位大侠给解决一下