調用百度雲Api實現從百度雲盤自動下載文件


                  一、注冊賬號

                要從百度雲下載文件,首先,注冊一個百度雲賬號,現在可能都要注冊手機號啦,當然,如果你已經注冊過,很幸運,就可以省略掉此步驟啦。

                  如圖登錄后所示:

                      點擊Access Key,即顯示上面的圖示,創建的Access Key ID和Secret Access Key(點擊顯示與隱藏即可);或者點擊“創建Access Key”,可以創建一個新的Access Key。

                      二、安裝SDK工具包

                      這里提供一個鏈接,就是百度雲的Api(https://cloud.baidu.com/doc/BOS/C-Dotnet-SDK.html#.E6.A6.82.E8.BF.B0),可以下載一個SDK直接添加引用,或在自己的VS項目中右擊點擊“管理Nuget程序包”->搜索“BceSdkDotNet.dll”安裝即可。另外,記得第三方依賴工具包log4net.dllNewtonsoft.Json.dll也是需要添加的。

                    安裝BceSdkDotNet.dll如下:  

                      代碼如下:

using BaiduBce;
using BaiduBce.Auth;
using BaiduBce.Services.Bos;
using BaiduBce.Services.Bos.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBEN.ICEngine.BceSdkDotNet
{
    public static class FileDownLoadByBce
    {
        public static void FileDownLoad()
        {
            BosClient client = GenerateBosClient();
            const string bucketName = "/aaa";    //指定Bucket名稱(文件夾名稱)
            const string objectKey = "a.zip";     //指定object名稱(文件名字)// 獲取Object
            BosObject bosObject = client.GetObject(bucketName, objectKey);
            // 獲取ObjectMeta
            ObjectMetadata meta = bosObject.ObjectMetadata;
            // 獲取Object的輸入流
            Stream objectContent = bosObject.ObjectContent;
            // 處理Object
            FileStream fileStream = new FileInfo(objectKey).OpenWrite();      //指定下載文件的目錄/文件名
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = objectContent.Read(buffer, 0, buffer.Length)) > 0)
            {
                fileStream.Write(buffer, 0, count);
            }

            // 關閉流
            objectContent.Close();
            fileStream.Close();
        }

        private static BosClient GenerateBosClient()
        {
            const string accessKeyId = "bea84b49522e4b6bb31ee286b2716cf3"; // 您的Access Key ID
            const string secretAccessKey = ""; // 您的Secret Access Key
            const string endpoint ="www.baidu.com";        //指定Bucket所在區域域名

            // 初始化一個BosClient
            BceClientConfiguration config = new BceClientConfiguration();
            config.Credentials = new DefaultBceCredentials(accessKeyId, secretAccessKey);
            config.Endpoint = endpoint;

            return new BosClient(config);
        }
    }
}

                     建立百度雲盤是需要付費的。。。就寫到這里啦。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM