我正在开发一个需要上传内容到FTP的应用程序。 我一直无法使apache commons与文件上传工作。上传的文件有0个字节。我尝试使用相同结果的ASCII和二进制模式。 这是我的代码
Log.d("FTP", "Connecting");
ftpsClient.connect(server,port);
if(ftpsClient.isConnected())
{
Log.d("FTP", "Sending File");
ftpsClient.login("XXXXXXX", "XXXXXXXX");
ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream is = new FileInputStream("sdcard/log.txt");
ftpsClient.storeFile("log.txt", is);
is.close();
ftpsClient.logout();
ftpsClient.disconnect();
}
我做错了什么?
答案 0 :(得分:4)
在那里,完成了,看到了完全相同的问题。
在
ftpsClient.login("XXXXXXX", "XXXXXXXX");
添加
ftpsClient.enterLocalPassiveMode();
为了扩大答案,这里有一个完整的进展片段:
private class FTPUploadTask extends AsyncTask<AFileDescriptor, Long, Boolean> {
private static final int bufferSize = 64;
private boolean isCanceling = false;
private long fileSize = 0;
private ProgressDialog pd;
@Override
protected void onPreExecute() {
pd = new ProgressDialog( ThisActivity.this );
pd.setCancelable( false );
pd.setMessage( "Uploading something..." );
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.setMax(100);
pd.show();
}
@Override
protected void onProgressUpdate(Long... progress) {
pd.setProgress( (int)( progress[0] * 100 / fileSize ) );
}
private int storeFile( OutputStream out, String local ) {
try {
InputStream in = new FileInputStream( local );
byte[] buffer = new byte[ bufferSize * 1024 ];
int read;
int allRead = 0;
while( ( ( read = in.read( buffer ) ) != - 1 ) && !isCanceling ) {
allRead += read;
this.publishProgress( (long) allRead );
out.write( buffer, 0, read );
}
in.close();
in = null;
out.flush();
out.close();
out = null;
return allRead;
} catch( Throwable th ) {
Log.d( "Error: ", th.getMessage() );
return -1;
}
}
@Override
protected Boolean doInBackground( AFileDescriptor... params ) {
ASubFileDescriptor file = params[0].getDefaultFile();
FTPClient ftp = new FTPClient();
try {
ftp.connect( FTPHostName );
ftp.login( FTPUser, FTPPass );
ftp.cwd( FTPTargetFolder );
ftp.enterLocalPassiveMode();
String storeName = file.getStoreName();
ftp.setFileType( FTP.BINARY_FILE_TYPE );
this.fileSize = file.getFile().length();
OutputStream out = ftp.storeFileStream( storeName );
int bytes = storeFile( out,
file.getFile().getAbsolutePath() );
ftp.logout();
ftp.disconnect();
return bytes > 0;
} catch( Throwable th ) {
Log.d( "FTP Error:", th.getMessage() );
return false;
}
}
@Override
protected void onPostExecute( Boolean success ) {
try {
pd.dismiss();
} catch( Throwable th ) {
}
if( success ) {
// do something
} else {
// do something else
}
}
此代码段用于将某些调试信息上载到本地服务器以获得2级支持。根据您使用上传的方式,您可能需要添加更多错误检查/恢复和用户交互。