Home » Android » Android – Download all files from a folder on server

Android – Download all files from a folder on server

Posted by: admin June 15, 2020 Leave a comment

Questions:

Hope I am able to explain this correctly…
I am able to connect to my web server and download a single file.What I am now attempting to do is connect to my server and download all the flies from a particular folder.In this case i want to download images.
This is the code i use to download a single file…

URL url  = new URL("http://127.0.0.1/Folder/file.csv");
            URLConnection conexion = url.openConnection();
            conexion.connect();
            int lenghtOfFile = conexion.getContentLength();
            InputStream is = url.openStream();
            File testDirectory = 
            new File(Environment.getExternalStorageDirectory()+"/Folder");
            if(!testDirectory.exists()){
                testDirectory.mkdir();
            }
            FileOutputStream fos = new FileOutputStream(testDirectory+"/file.csv");
            byte data[] = new byte[1024];
            int count = 0;
            long total = 0;
            int progress = 0;
            while ((count=is.read(data)) != -1){
                total += count;
                int progress_temp = (int)total*100/lenghtOfFile;
                if(progress_temp%10 == 0 && progress != progress_temp){
                    progress = progress_temp;
                }
                fos.write(data, 0, count);
            }
            is.close();
            fos.close();

How can I add to this code to make it download all the files from that folder?

How to&Answers:

I would suggest you to have a script at server’s end, which first gives you list of all the files inside a folder, and then your application downloads each file one by one.

Answer:

public class DownloadFileService extends Service implements ConfigCommonVars {

private static final int NOTIFICATION = 0;
private NotificationManager mNM;
File SDCardRoot = Environment.getExternalStorageDirectory();

ArrayList<String> mServerFileListApp = new ArrayList<String>();
ArrayList<String> mDeviceFileListApp = new ArrayList<String>();

@Override
public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // Display a notification about us starting.  We put an icon in the status bar.
    showNotification();
    Toast.makeText(this, " device Services ",Toast.LENGTH_LONG).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.

    File directory = new File(SDCardRoot+DOC_FOLDER_NAME);

    // create directory if not exists 
    if(!directory.exists())
    {
        if(directory.mkdirs()) //directory is created;
            Log.i(" download ","App dir created");
        else 
            Log.w(" download ","Unable to create app dir!");
    }

    mDeviceFileListApp = getDeviceFiles();
    Toast.makeText(this, " device file  "+mDeviceFileListApp.toString(),Toast.LENGTH_LONG).show();

      new Thread(new Runnable() {
            public void run() { 
                try {
                    mServerFileListApp = getServerFiles();
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
         }).start();

    return START_STICKY;
}

@Override
public void onDestroy() {
    // Cancel the persistent notification.
    mNM.cancel(NOTIFICATION);

    // Tell the user we stopped.
    Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}

private void showNotification() {

    /*// In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.local_service_started);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.stat_sample, text,System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, this.Controller.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.local_service_label),text, contentIntent);

    // Send the notification.
    mNM.notify(NOTIFICATION, notification);
    */

}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public ArrayList<String> getDeviceFiles()
{
    mDeviceFileListApp = new ArrayList<String>();

    File directory = new File(SDCardRoot+DOC_FOLDER_NAME);
    if(directory.length()!=0) // check no of files 
    {
        for (File file : directory.listFiles()) {
            if (file.isFile())
                mDeviceFileListApp.add(file.getName());        
        }
    }
    return mDeviceFileListApp;
}

public ArrayList<String>  getServerFiles()
{
    InputStream inputStream = null;
    JSONArray mFileArray = null;
    String mfileNames ;
    mServerFileListApp = new ArrayList<String>();


    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(HTTP+SITE_URL+WEB_SERVICES_PATH+"bmservicecontroller.php?PAGE=loginpage&OPTION=downloadFile&TYPE=1");

    // get list of file in download folder 
    try
    {
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity httpEntity = response.getEntity();
        inputStream = httpEntity.getContent();

        BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder builder= new StringBuilder();
        char[] buf = new char[1000];
        int l = 0;
        while (l >= 0)
        {
            builder.append(buf, 0, l);
            l = reader.read(buf);
        }
        inputStream.close();

        JSONTokener tokener = new JSONTokener( builder.toString());
        JSONObject finalResult = new JSONObject( tokener );

        mFileArray = finalResult.getJSONObject("FSSEAPI").getJSONArray("FileName");

        for (int i = 0; i < mFileArray.length(); i++)
        {
            try {
                mfileNames = mFileArray.getString(i);
                mServerFileListApp.add(mfileNames);

            } catch (Exception e) {
                //showError("File Not Found " + mfileNames);
                e.printStackTrace();
            }
        } // for ends

        String temp;
        for (int i=0; i<mServerFileListApp.size(); i++)
        {
            temp = mServerFileListApp.get(i);
            if(! mDeviceFileListApp.contains(temp))
            {
                Log.i(" File Download Start ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
                downloadFileManager(HTTP+SITE_URL+DOWNLOAD_PATH,temp);                  
            }
            else
            {
                // check and Delete File Exists
                Log.i(" File Deleted  ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
                /*
                File checkFile = new File(SDCardRoot+DOC_FOLDER_NAME+temp);

                if(checkFile.exists())
                    if(checkFile.delete())
                        Log.i(" File Deleted  ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
                    else 
                        Log.i(" File Not Delete ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
                */
            }
        }

    }
    catch(IOException e)
    {
        e.printStackTrace();
        //showError("File Download Error ");
    }
    catch (JSONException e)
    {
        e.printStackTrace();
        //showError("File Download Error ");
    }

    return mServerFileListApp;  
}

public void downloadFileManager(String path,String file)
{
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(path+file));
    request.setDescription(file+"descrition");
    request.setTitle(file+"title");
    // in order for this if to run, you must use the android 3.2 to compile your app
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        //request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir(DOC_FOLDER_NAME, file);

    // get download service and enqueue file
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}
}