[英]How can i upload a file into a ftp server?
解决了
我正在进行必须与ftp服务器联系的桌面应用程序,将要上传的文件是图像。 我正在尝试,但是尽管已连接但无法上传,问题是当我想上传文件时,该方法不起作用并返回false。 代码如下:
public boolean subeFTP(String archivoLocal, String archivoServer){
boolean resultado=false;
FTPClient ClienteFTP=new FTPClient();
//Se toma el nombre del archivo local
String aux = archivoLocal;
aux = aux.substring(aux.lastIndexOf("\\")+1);
try {
//Establece el timeout del servidor en 5 minutos para evitar desconexiones
ClienteFTP.setControlKeepAliveTimeout(300);
//Conexión al servidor
ClienteFTP.connect(prop_servidor, prop_puertoServidor);
//Pone el ftp en modo pasivo para recibir un archivo, permanecerá así mientras no se cambie
ClienteFTP.enterLocalPassiveMode();
//Login
resultado=ClienteFTP.login(prop_usuarioFtp, prop_passFtp);
//Comprobación de la conexión
int reply = ClienteFTP.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ClienteFTP.logout();
ClienteFTP.disconnect();
throw new Exception("El servidor FTP ha rechazado la conexión, error:\n" + ClienteFTP.getReplyString());
}
//Se cambia el directorio al requerido
resultado = resultado && ClienteFTP.changeWorkingDirectory(prop_directorioServidor);
//Tipo de archivo y envío
resultado = resultado && ClienteFTP.setFileType(FTP.BINARY_FILE_TYPE);
//resultado = resultado && ClienteFTP.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
BufferedInputStream buffIn=new BufferedInputStream(new FileInputStream(archivoLocal));
resultado = resultado && ClienteFTP.storeFile(archivoServer+aux, buffIn);
System.out.println(ClienteFTP.getReplyString());
buffIn.close();
ClienteFTP.logout();
ClienteFTP.disconnect();
resultado=true;
} catch (SocketException e) {
System.out.println("Fallo 1");
e.printStackTrace();
resultado=false;
} catch (IOException e) {
System.out.println("Fallo 2");
resultado=false;
e.printStackTrace();
} catch (Exception e) {
resultado=false;
e.printStackTrace();
}
return resultado ;
}
您应该进入本地被动模式。 使用以下方法ftp.enterLocalPassiveMode()
根据文件
将当前数据连接模式设置为PASSIVE_LOCAL_DATA_CONNECTION_MODE。 仅在客户端和服务器之间的数据传输时使用此方法。 此方法导致在打开每个数据连接之前向服务器发出PASV(或EPSV)命令,告诉服务器打开客户端将连接到的数据端口以进行数据传输。 FTPClient将保持在PASSIVE_LOCAL_DATA_CONNECTION_MODE,直到通过调用某些其他方法(例如enterLocalActiveMode())更改模式为止。
我也建议您调用ftpClient.setControlKeepAliveTimeout(timeoutInMilliseconds);
Set the time to wait between sending control connection keepalive messages when processing file upload or download.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.