提供一個思路,你們能夠參考着修改本身的方法! url
/**
* 上傳文件到FTP
*
* @param file
* file文件,struts2從頁面獲得的File類型
*
* @param filePath
* 要保存在FTP上的路徑(文件夾)
* @param fileName
*
*
* @return 文件是否上傳成功
*
* @throws Exception
*/.net
public static boolean upload(File file, String filePath, String fileName) {ci
TelnetOutputStream to = null;get
FileInputStream fi = null;it
filePath = FILE_SEPARATOR (定義的路徑獲取)+ filePath;io
try {
if (file != null) {class
connectFTP();
// ftpClient.setAsciiType();struts2
if (!isDirExist(filePath.replace("\\", "/"))) {ftp
createDir(filePath.replace("\\", "/"));file
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();
}
}