已解决
我正在制作一个必须与 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()
根据文档
Set the current data connection mode to PASSIVE_LOCAL_DATA_CONNECTION_MODE . Use this method only for data transfers between the client and server. This method causes a PASV (or EPSV) command to be issued to the server before the opening of every data connection, telling the server to open a data port to which the client will connect to conduct data transfers. The FTPClient will stay in PASSIVE_LOCAL_DATA_CONNECTION_MODE until the mode is changed by calling some other method such as enterLocalActiveMode()
我还建议您调用ftpClient.setControlKeepAliveTimeout(timeoutInMilliseconds);
Set the time to wait between sending control connection keepalive messages when processing file upload or download.
关于java - 如何将文件上传到 ftp 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460289/