1. 程式人生 > >使用FileDownLoader下載檔案

使用FileDownLoader下載檔案

關於FileDownLoader這個下載引擎在這裡我就不多做介紹了,具體可以開啟github上的地址FileDownLoader 檢視~

部落格結尾處也有簡略說明

使用FileDownLoader

第一步:如果使用的是AndroidStudio開發工具,需要在專案中引用:

  1. compile 'com.liulishuo.filedownloader:library:1.3.0'  
第二步:然後在Application.Oncreate  中進行全域性初始化
  1. public XXApplication extends Application{  
  2.     ...  
  3.     @Override
  4.     publicvoid onCreate() {  
  5.         /** 
  6.          * 僅僅是快取Application的Context,不耗時 
  7.          */
  8.         FileDownloader.init(getApplicationContext);  
  9.     }  
  10.     ...  
  11. }  

啟動單任務下載

FileDownloader.getImpl().create(url)
        .setPath(path)
        .setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }

            @Override
            protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();

下載介紹一下我寫的單例下載:

1.單任務下載

  1. <span style="font-size:14px;">package com.kuaibao.skuaidi.manager;  
  2. import com.liulishuo.filedownloader.BaseDownloadTask;  
  3. import com.liulishuo.filedownloader.FileDownloadListener;  
  4. import com.liulishuo.filedownloader.FileDownloader;  
  5. /** 
  6.  * Created by gudd
     
  7.  * on 2016/10/27. 
  8.  * compile 'com.liulishuo.filedownloader:library:1.3.0' 
  9.  */
  10. publicclass FileDownloaderManager {  
  11.     publicstatic FileDownloaderManager instance = null;  
  12.     private FileDownloaderManager() {  
  13.     }// 避免類在外部被例項化
  14.     publicstatic FileDownloaderManager getInstance() {  
  15.         if (null == instance) {  
  16.             instance = new FileDownloaderManager();  
  17.         }  
  18.         return instance;  
  19.     }  
  20.     /** 
  21.      * 單任務下載 
  22.      * 
  23.      * @param downLoadUri  檔案下載網路地址 
  24.      * @param destinationUri 下載檔案的儲存絕對路徑 
  25.      */
  26.     publicvoid startDownLoadFileSingle(String downLoadUri, String destinationUri,FileDownLoaderCallBack callBack) {  
  27.         FileDownloader.getImpl().create(downLoadUri).setPath(destinationUri).setListener(fileDownloadListener(callBack)).start();  
  28.     }  
  29. // 下載方法
  30.     private FileDownloadListener fileDownloadListener(final FileDownLoaderCallBack callBack) {  
  31.         returnnew FileDownloadListener() {  
  32.             @Override
  33.             protectedvoid pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {  
  34.                 //等待,已經進入下載佇列
  35.             }  
  36.             @Override
  37.             protectedvoid progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {  
  38.                 //下載進度回撥
  39.                 if (callBack != null){  
  40.                     callBack.downLoadProgress(task,soFarBytes,totalBytes);  
  41.                 }  
  42.             }  
  43.             @Override
  44.             protectedvoid completed(BaseDownloadTask task) {  
  45.                 //完成整個下載過程
  46.                 if (callBack != null){  
  47.                     callBack.downLoadComplated(task);  
  48.                 }  
  49.             }  
  50.             @Override
  51.             protectedvoid paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {  
  52.                 //暫停下載
  53.             }  
  54.             @Override
  55.             protectedvoid error(BaseDownloadTask task, Throwable e) {  
  56.                 //下載出現錯誤
  57.                 if (callBack != null){  
  58.                     callBack.downLoadError(task,e);  
  59.                 }  
  60.             }  
  61.             @Override
  62.             protectedvoid warn(BaseDownloadTask task) {  
  63.                 //在下載佇列中(正在等待/正在下載)已經存在相同下載連線與相同儲存路徑的任務
  64.             }  
  65.         };  
  66.     }  
  67.     // 這裡是下載過程中的回撥,由於下載過程中,我們只需要知道檔案是否下載完成、檔案是否下載失敗、還有檔案下載進度,</span>

所以這裡只自定義三個方法用於回撥 

  1. <span style="font-size:14px;">
  2.     publicinterface FileDownLoaderCallBack{  
  3.         void downLoadComplated(BaseDownloadTask task);  
  4.         void downLoadError(BaseDownloadTask task, Throwable e);  
  5.         void downLoadProgress(BaseDownloadTask task, int soFarBytes, int totalBytes);  
  6.     }  
  7. }</span> 

所以,你在使用的時候只需要使用一行程式碼就可以下載檔案了:

  1. FileDownloaderManager.getInstance().startDownLoadFileSingle("下載地址",“儲存地址”,new FileDownLoaderCallBack({  
  2. ......  
  3. }));  

啟動多工下載

final FileDownloadListener queueTarget = new FileDownloadListener() {
    @Override
    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    }

    @Override
    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
    }

    @Override
    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    }

    @Override
    protected void blockComplete(BaseDownloadTask task) {
    }

    @Override
    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
    }

    @Override
    protected void completed(BaseDownloadTask task) {
    }

    @Override
    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    }

    @Override
    protected void error(BaseDownloadTask task, Throwable e) {
    }

    @Override
    protected void warn(BaseDownloadTask task) {
    }
};

// 第一種方式 :

//for (String url : URLS) {
//    FileDownloader.getImpl().create(url)
//            .setCallbackProgressTimes(0) // 由於是佇列任務, 這裡是我們假設了現在不需要每個任務都回調`FileDownloadListener#progress`, 我們只關係每個任務是否完成, 所以這裡這樣設定可以很有效的減少ipc.
//            .setListener(queueTarget)
//            .asInQueueTask()
//            .enqueue();
//}

//if(serial){
    // 序列執行該佇列
//    FileDownloader.getImpl().start(queueTarget, true);
// }

// if(parallel){
    // 並行執行該佇列
//    FileDownloader.getImpl().start(queueTarget, false);
//}

// 第二種方式:

final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener);

final List<BaseDownloadTask> tasks = new ArrayList<>();
for (int i = 0; i < count; i++) {
     tasks.add(FileDownloader.getImpl().create(Constant.URLS[i]).setTag(i + 1));
}

queueSet.disableCallbackProgressTimes(); // 由於是佇列任務, 這裡是我們假設了現在不需要每個任務都回調`FileDownloadListener#progress`, 我們只關係每個任務是否完成, 所以這裡這樣設定可以很有效的減少ipc.

// 所有任務在下載失敗的時候都自動重試一次
queueSet.setAutoRetryTimes(1);

if (serial) {
  // 序列執行該任務佇列
     queueSet.downloadSequentially(tasks);
     // 如果你的任務不是一個List,可以考慮使用下面的方式,可讀性更強
//      queueSet.downloadSequentially(
//              FileDownloader.getImpl().create(url).setPath(...),
//              FileDownloader.getImpl().create(url).addHeader(...,...),
//              FileDownloader.getImpl().create(url).setPath(...)
//      );
}

if (parallel) {
  // 並行執行該任務佇列
   queueSet.downloadTogether(tasks);
   // 如果你的任務不是一個List,可以考慮使用下面的方式,可讀性更強
//    queueSet.downloadTogether(
//            FileDownloader.getImpl().create(url).setPath(...),
//            FileDownloader.getImpl().create(url).setPath(...),
//            FileDownloader.getImpl().create(url).setSyncCallback(true)
//    );
}

// 序列任務動態管理也可以使用FileDownloadSerialQueue。

全域性介面說明(FileDownloader)

從youtube快速下載檔案到本地的方案

需要的軟體(工具): 一 vps(我使用的是搬瓦工 https://bwh1.net/) 二 百度網盤客戶端(需要vip會員加速) 步驟: 一 在搬瓦工vps中安裝youtube-dl (https://github.com/rg3/youtube-dl),安裝完後在vps上下

成功解決Git Bash執行指令碼命令下載檔案到預設C盤路徑的問題

解決問題 解決Git Bash執行指令碼命令下載檔案到預設C盤路徑的問題 1、預設下載到資料夾為   解決思路 %homedrive%    指作業系統所在盤%homepath%      指\Docum

實現從oss(阿里雲)伺服器以附件形式下載檔案(含批量下載

轉載自:https://blog.csdn.net/sinat_28771747/article/details/53520253 筆者在專案中寫一個從阿里雲伺服器上面以附件形式下載檔案的介面時,遇到了問題,網上搜索無任何相關的解決方案,最後通過通過自己查閱API文件,再結合自己的經驗,實現了下

iframe標籤實現form表單提交下載檔案

一、表單提交的程式碼常規寫法 <iframe name="testIframeName" style="display:none;"></iframe> <form target="testIframeName" method="post" acti

轉發:傳送post請求下載檔案

原文地址:https://blog.csdn.net/yunlala_/article/details/78385962 處理檔案流方案一 以下是我親試可以實現的一種方案: exportData () { const form = this.getSearc

Postman高階應用(8):檔案變成了亂碼——下載檔案

背景 在做後臺管理系統時候,涉及到匯出報表等功能,如果我們用以前的方式請求,往往會看到返回一堆亂碼,而不是我們想要的檔案。其實Postman為我們提供了檔案下載功能,同樣普通的html文字和json資料也可以返回儲存為檔案。 實戰 點發送按鈕旁邊的三角形,然後點Send a

利用IO流一次性讀取檔案中的所有內容,利用IO流下載檔案

利用IO流一次性讀取檔案中的所有內容 讀取檔案效率最快的方法就是一次全讀進來,使用readline()之類的方法,可能需要反覆訪問檔案,而且每次readline()都會呼叫編碼轉換,降低了速度,所以,在已知編碼的情況下,按位元組流方式先將檔案都讀入記憶體,再一次性編碼轉換是最快的方式

C程式碼實現從FTP上下載檔案

從FTP上下載檔案這個功能我早就想實現了,但是苦於百度的文章大多是下載連結,一直沒捨得積分下載,這次通過查閱MSDN,將一套下載流程函式摸了一下,寫出程式碼實現從FTP下載檔案 環境 VS2015 程式碼: #include <iostream> #include <

SpringMVC 使用MultipartResolver下載檔案

MultipartResolver 用於處理檔案上傳,當收到請求時 DispatcherServlet 的 checkMultipart() 方法會呼叫 MultipartResolver 的 isMultipart() 方法判斷請求中是否包含檔案。如果請求資料中包含檔案,則呼叫 

java下載檔案注意點

前臺: 不建議使用ajax,可以使用window.location.href   後臺: 三個引數--> response path filename--filename如果要防止亂碼,可以用String str = URLEncoder.encode("中國","utf-8")

ueditor上傳圖片不好用,訪問ueditor中的controller.js變成下載檔案

由於疏忽了web.xml中的servlet配置問題,將urlpattern配置成了"/" <servlet-mapping>     <servlet-name>test</servlet-name>  &

Android AsyncHttpClient 下載檔案 Content-Type not allowed! 錯誤

專案開發更新版本時候下載apk使用AsyncHttpClient 及BinaryHttpResponseHandler來處理 但總是報errororg.apache.http.client.HttpResponseException: Content-Type not allowed! 錯誤

Struts2下載檔案點取消、重複下載出現的異常解決

在使用Struts2下載檔案時,如果重複下載,會丟擲如下異常: java.lang.IllegalStateException: Cannot call sendError() after the response has been committed at org

如何將IOS版本的更新下載檔案指向到自己的伺服器

針對那些使用企業簽名但是沒有釋出到AppSotre的IOS版本APP自動更新問題解決方案: 在apicloud中是這樣說明的: 因為要填寫plist地址所以不能向安卓那樣直接填寫伺服器檔案地址,但是直接填寫apicloud中的包又沒有簽名,所以我們用以下方式解決: 首先我們找到編譯記錄中的地址 例

linux利用scp遠端上傳下載檔案/資料夾

scp是secure copy的簡寫,用於在Linux下進行遠端拷貝檔案的命令,和它類似的命令有cp,不過cp只是在本機進行拷貝不能跨伺服器,而且scp傳輸是加密的。可能會稍微影響一下速度。 當你伺服器硬碟變為只讀 read only system時,用scp可

JS實現點選按鈕,下載檔案

今天在實現下載功能時,後臺介面測試完成後,前臺在呼叫時發現,因為系統是基於token的,又不想把token顯示在url中,後來找到了一篇文章,講解了如何通過構造form表單提交請求後端介面,實現檔案下載,原文地址:https://www.cnblogs.com/hamsterPP/p/6763458.html

webdriver API:上傳下載檔案

上傳檔案 普通上傳:將本地檔案的路徑作為一個值放在input標籤中,通過form表單提交的時候將這個值提交給伺服器 上傳的輸入框標籤必須為input #送一個檔案的絕對路徑到上傳輸入框 dr.find_element_by_name('file').send_keys('D:\\uplo