¿Subir un archivo a un servidor FTP desde un teléfono Android?
A continuación se muestra el código que se supone que debe crear un documento de texto y subirlo a mi servidor FTP. Por alguna razón, no parece funcionar. Me acostumbraba a las bibliotecas proporcionadas en
Http://lavalatwork.blogspot.tw/2010/09/using-apache-commons-ftp-library-in.html
- Biblioteca de AndroidFillableLoaders de JorgeCastilloPrz - Problema de SVGPath
- Combo de IdentityHashMap y WeakHashMap
- Varias llaves y valores de JSONObject no se guardarán en Parse
- Decompile archivos .smali en un APK
- Haciendo la vista de lista de android desplazable
Para comunicarse con el servidor FTP.
try { final String testString = new String("Hello"); FileOutputStream fOut = openFileOutput("samplefile.txt", MODE_WORLD_READABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(testString); osw.flush(); osw.close(); } catch(IOException ex) { } FTPClient mFTP = new FTPClient(); try { // Connect to FTP Server mFTP.connect("192.168.10.101"); //mFTP.login("user", "password"); mFTP.setFileType(FTP.BINARY_FILE_TYPE); mFTP.enterLocalPassiveMode(); // Prepare file to be uploaded to FTP Server File file = new File(getFileStreamPath("samplefile.txt")+ ""); FileInputStream ifile = new FileInputStream(file); // Upload file to FTP Server mFTP.storeFile("filetotranfer",ifile); mFTP.disconnect(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Cualquier ayuda sería apreciada.
- ¿Cómo debo estructurar mi proyecto para compartir clases entre una aplicación cliente de Android y una aplicación de servidor JSP?
- Android: adb shell, no se encontró ningún comando adb
- JUnit - ComparisonFailure en la cadena formateada
- AlertDialog y teclado blando
- Asegúrese de que el nombre de clase existe, es público y tiene un constructor vacío para fragmento público con nombre de clase y constructor vacío
- Android RecyclerView Adapter está dando nulo en la prueba de unidad
- Biblioteca de visor de PDF de Android o tutoriales de biblioteca de muPDF
- Android java.lang.ClassNotFoundException
Vea esto …… Esto le ayudará a rectificar los probs en su código.
He utilizado la biblioteca común de apache para cargar y descargar un archivo de audio desde y hacia el servidor … ver esto …
Carga:
public void goforIt(){ FTPClient con = null; try { con = new FTPClient(); con.connect("192.168.2.57"); if (con.login("Administrator", "KUjWbk")) { con.enterLocalPassiveMode(); // important! con.setFileType(FTP.BINARY_FILE_TYPE); String data = "/sdcard/vivekm4a.m4a"; FileInputStream in = new FileInputStream(new File(data)); boolean result = con.storeFile("/vivekm4a.m4a", in); in.close(); if (result) Log.v("upload result", "succeeded"); con.logout(); con.disconnect(); } } catch (Exception e) { e.printStackTrace(); } }
Descargando:
public void goforIt(){ FTPClient con = null; try { con = new FTPClient(); con.connect("192.168.2.57"); if (con.login("Administrator", "KUjWbk")) { con.enterLocalPassiveMode(); // important! con.setFileType(FTP.BINARY_FILE_TYPE); String data = "/sdcard/vivekm4a.m4a"; OutputStream out = new FileOutputStream(new File(data)); boolean result = con.retrieveFile("vivekm4a.m4a", out); out.close(); if (result) Log.v("download result", "succeeded"); con.logout(); con.disconnect(); } } catch (Exception e) { Log.v("download result","failed"); e.printStackTrace(); } }
Puede utilizar Simple Java FTP Client y agregarlo como jar externel para su proyección, también puede referirse a este enlace
public class FileUpload { /** * Upload a file to a FTP server. A FTP URL is generated with the * following syntax: * ftp://user:password@host:port/filePath;type=i. * * @param ftpServer , FTP server address (optional port ':portNumber'). * @param user , Optional user name to login. * @param password , Optional password for user. * @param fileName , Destination file name on FTP server (with optional * preceding relative path, eg "myDir/myFile.txt"). * @param source , Source file to upload. * @throws MalformedURLException, IOException on error. */ public void upload( String ftpServer, String user, String password, String fileName, File source ) throws MalformedURLException, IOException { if (ftpServer != null && fileName != null && source != null) { StringBuffer sb = new StringBuffer( "ftp://" ); // check for authentication else assume its anonymous access. if (user != null && password != null) { sb.append( user ); sb.append( ':' ); sb.append( password ); sb.append( '@' ); } sb.append( ftpServer ); sb.append( '/' ); sb.append( fileName ); /* * type ==> a=ASCII mode, i=image (binary) mode, d= file directory * listing */ sb.append( ";type=i" ); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL( sb.toString() ); URLConnection urlc = url.openConnection(); bos = new BufferedOutputStream( urlc.getOutputStream() ); bis = new BufferedInputStream( new FileInputStream( source ) ); int i; // read byte by byte until end of stream while ((i = bis.read()) != -1) { bos.write( i ); } } finally { if (bis != null) try { bis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } else { System.out.println( "Input not available." ); } }
También puede usar la biblioteca Apache commons-net-ftp , para más detalles puede centrarse en este enlace .
import org.apache.commons.net.ftp.FTPClient; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(InetAddress.getByName(SERVER)); ftpClient.login(USERNAME, PASSWORD); ftpClient.changeWorkingDirectory(PATH); if (ftpClient.getReplyString().contains("250")) { ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = null; buffIn = new BufferedInputStream(new FileInputStream(FULL_PATH_TO_LOCAL_FILE)); ftpClient.enterLocalPassiveMode(); ProgressInputStream progressInput = new ProgressInputStream(buffIn, progressHandler); boolean result = ftpClient.storeFile(localAsset.getFileName(), progressInput); buffIn.close(); ftpClient.logout(); ftpClient.disconnect(); } } catch (SocketException e) { Log.e(SorensonApplication.TAG, e.getStackTrace().toString()); } catch (UnknownHostException e) { Log.e(SorensonApplication.TAG, e.getStackTrace().toString()); } catch (IOException e) { Log.e(SorensonApplication.TAG, e.getStackTrace().toString()); }
Aquí está el bloque de código:
private class UploadFile extends AsyncTask<String, Integer, Boolean> { @Override protected Boolean doInBackground(String... params) { FTPClient client = new FTPClient(); try { client.connect(params[1], PORT); client.login(params[2], params[3]); client.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); return client.storeFile(filename, new FileInputStream(new File( params[0]))); } catch (Exception e) { Log.d("FTP", e.toString()); return false; } } @Override protected void onPostExecute(Boolean sucess) { if (sucess) Toast.makeText(activity, "File Sent", Toast.LENGTH_LONG).show(); else Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show(); } }
Por favor, obtenga proyecto de trabajo completo para subir archivos a servidor FTP desde debajo de la unidad.
Archivo de carga a FTP se utiliza puerto 21, parámetro necesario para cargar archivos en FTP ..
Nombre de host nombre de usuario contraseña
https://drive.google.com/file/d/0B80LBJs3JkaDYUNfZ3pDSkVJUDA/edit