2011-12-27 97 views
1

我試圖從網絡上將文件保存到我的Android設備,但我不知道該怎麼做。 URL地址打開一個空白頁面和一個彈出下載框,其中包含我想要下載的文件,以便我可以選擇將其保存到哪裏。使用android下載文件

我的問題是,我不知道如何管理該框以下載文件。這不像我想下載該頁面上顯示的內容,因爲該頁面是空白的。所以我不能使用此代碼:

  Context context = thisClass.this; 
     Drawable image = ImageOperations(context, 
      "http://android.okhelp.cz/images/adictionary/ad_4.png" 
      ,"image.jpg"); 
     ImageView imgView; 
     imgView = (ImageView)findViewById(R.id.idImageView); 
     imgView.setImageDrawable(image); 

private Drawable ImageOperations(Context ctx, String url, String saveFilename) { 
    try { 
     InputStream is = (InputStream) this.fetch(url); 
     Drawable d = Drawable.createFromStream(is, "src"); 
     return d; 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
     return null; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

public Object fetch(String address) throws MalformedURLException,IOException { 
    URL url = new URL(address); 
    Object content = url.getContent(); 
    return content; 
} 

我將不勝感激,如果有人能指出我哪裏開始尋找或給我一個解決方案。

+0

你不只是有一個直接鏈接到文件?如果是這樣,您可以下載它並將其保存在SD卡上或數據庫中。 – Dante 2011-12-27 13:35:21

+0

不,我無法使用手機下載文件,因爲該網站的移動版本不允許我下載該文件。我只能使用我的電腦下載它,然後從電腦上將它傳輸到我的手機。但是如果可能的話,我想避免這種情況。 – Lara 2011-12-27 13:49:44

+0

我不是在談論到該網站的鏈接,而是在談論與該文件的直接鏈接。你能告訴我網站的鏈接和你想下載的文件嗎? – Dante 2011-12-27 13:51:11

回答

1

我解決了它!

  File card2= Environment.getExternalStorageDirectory(); 
      File dir2= new File (card2.getAbsolutePath()+"/MyFiles"); 
      dir2.mkdirs(); 
      new DefaultHttpClient().execute(new HttpGet(your_url_here-this_is_a_string)).getEntity().writeTo(
      new FileOutputStream(new File(dir2,your_file_on_sdcard-this_is_string))); 

這也被try/catch包圍。並記住在地址前插入協議,否則它將無法工作! 希望它有幫助!