2011-02-17 190 views
8

希望我能夠正確解釋此... 我能夠連接到我的Web服務器並下載一個文件。我現在試圖做的是連接到我的服務器,並從一個特定的文件夾下載所有的蒼蠅。在這種情況下,我想下載圖像。 這是我用它來下載一個文件的代碼...Android - 從服務器上的文件夾下載所有文件

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(); 

我如何可以添加到這個代碼,使其下載該文件夾中的所有文件?

+0

嘿,我需要幫助下載文件使用AS3到我的android。你說這個腳本有用嗎?你能幫我搞定它,因爲它不適合我嗎? – 2012-08-17 17:54:12

+0

我只需要單個文件下載 – 2012-08-17 17:54:29

回答

7

我建議你在服務器端有一個腳本,它首先給你一個文件夾內所有文件的列表,然後你的應用程序逐一下載每個文件。

3
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); 
} 
} 
相關問題