提供一个思路,大家可以参考着修改自己的方法!
/** * 上传文件到FTP * * @param file * file文件,struts2从页面得到的File类型 * * @param filePath * 要保存在FTP上的路径(文件夹) * @param fileName * * * @return 文件是否上传成功 * * @throws Exception */
public static boolean upload(File file, String filePath, String fileName) {
TelnetOutputStream to = null;
FileInputStream fi = null;
filePath = FILE_SEPARATOR (定义的路径获取)+ filePath;
try { if (file != null) {
connectFTP(); // ftpClient.setAsciiType();
if (!isDirExist(filePath.replace("\\", "/"))) {
createDir(filePath.replace("\\", "/"));
ftpClient.changeDirectory("/" + filePath.replace("\\", "/"));
}
fi = new FileInputStream(file);
to = (TelnetOutputStream) ftpClient.putFileStream(fileName, true);
byte[] bytes = new
byte[1024];
int i = fi.read(bytes);
while (i != -1) {
to.write(bytes);
i = fi.read(bytes); } }
return true;
} catch (FileNotFoundException e1) { e1.printStackTrace(); return false;
} catch (IOException e2) { e2.printStackTrace(); return false;
} catch (Exception e) { e.printStackTrace(); return false;
} finally {
if (fi != null) {
try { fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (to != null) {
try { to.flush();
to.close();
} catch (IOException e) { e.printStackTrace(); }
}
closeFTP();
}
}
/** * 链接FTP * * @throws FtpProtocolException */
public static void connectFTP() throws
FtpProtocolException {
try
{
ftpClient = FtpClient.create();
ftpClient.connect(new InetSocketAddress(url, port));
ftpClient.login(user, password.toCharArray());
ftpClient.setBinaryType();
} catch
(IOException e) {
e.printStackTrace();
}
}