NEWS

[C#] Hướng dẫn upload multifile lên google drive Api csharp

[C#] Hướng dẫn upload multifile lên google drive Api  csharp
Đăng bởi: Thảo Meo - Lượt xem: 28778 22:36:15, 23/07/2017DEVEXPRESS   In bài viết

Bài viết hôm nay, mình sẽ tiếp tục hướng dẫn các bạn cách upload nhiều file cùng một lúc lên google drive C#, sử dụng google drive api.

[C#] Upload multifile to Google Drive using google drive api v3

- Đầu tiên để upload được được lên google drive sử dụng api của google cung cấp, các bạn cần phải có một tài khoản gmail.

Giao diện demo ứng dụng:

upload multi file to google drive c#

Sau đó, các bạn tiếp tục vào đường dẫn sau để tạo một project với quyền sử dụng google drive api.

https://console.developers.google.com

Các bạn có thể tham khảo demo sample của google cung cấp ở đường dẫn bên dưới.

https://developers.google.com/drive/v3/web/quickstart/dotnet

- Các bạn nên đọc qua ví dụ mẫu google cung cấp, rồi tiếp tục đọc bài của mình nhé.

+ Tiếp theo chúng ta cần import thư viện Google Api vào. Chúng bạn có thể import thư viện bằng nuget console với cú pháp sau:

PM> Install-Package Google.Apis.Drive.v3

Sau khi các bạn import thư viên vào thành công.

Các bạn sử dụng source code của mình bên dưới để upload. 

Video demo ứng dụng:

Full source code upload multifile google drive:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Threading;

namespace GoogleDriver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        static string[] Scopes = { DriveService.Scope.Drive };
        static string ApplicationName = "Application_upload_file_laptrinh_vb";

        private  void ListFiles(DriveService service, ref string pageToken)
        {
            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 1;
            //listRequest.Fields = "nextPageToken, files(id, name)";
            listRequest.Fields = "nextPageToken, files(name)";
            listRequest.PageToken = pageToken;
            listRequest.Q = "mimeType='image/*'";

            // List files.
            var request = listRequest.Execute();


            if (request.Files != null && request.Files.Count > 0)
            {


                foreach (var file in request.Files)
                {
                    textBox1.Text += string.Format("{0}", file.Name);
                }

                pageToken = request.NextPageToken;

                if (request.NextPageToken != null)
                {
                    
                    Console.ReadLine();

                }

            }
            else
            {
               textBox1.Text +=("No files found.");
            }
        }

       

        private  void UploadImage(string path, DriveService service, string folderUpload)
        {
         

            var fileMetadata = new Google.Apis.Drive.v3.Data.File();
            fileMetadata.Name = Path.GetFileName(path);
            fileMetadata.MimeType = "image/*";
          
            fileMetadata.Parents = new List
            {
                folderUpload
            };


            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
            {
                request = service.Files.Create(fileMetadata, stream, "image/*");
                request.Fields = "id";
                request.Upload();
            }

            var file = request.ResponseBody;

            //textBox1.Text += ("File ID: " + file.Id);

        }


        private  UserCredential GetCredentials()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

                credPath = Path.Combine(credPath, "client_secreta.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                 textBox1.Text = string.Format("Credential file saved to: " + credPath);
            }

            return credential;
        }

     

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            UserCredential credential;

            credential = GetCredentials();

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
           
            string folderid;
            //get folder id by name
            var fileMetadatas = new Google.Apis.Drive.v3.Data.File()
            {
                Name = txtFolderNameUpload.Text,
                MimeType = "application/vnd.google-apps.folder"
            };
            var requests = service.Files.Create(fileMetadatas);
            requests.Fields = "id";
            var files = requests.Execute();
            folderid = files.Id;
           
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFileSelected.Text = "Đang upload file đến folder: => " + txtFolderNameUpload.Text + "

";
                foreach (string filename in openFileDialog1.FileNames)
                {
                    Thread thread = new Thread(() =>
                    {
                        UploadImage(filename, service, folderid);
                        txtFileSelected.Text += filename + " => upload thành công..." + "
";
                    });
                    thread.IsBackground = true;
                    thread.Start();
                   
                }
               
            }
         

            string pageToken = null;

            do
            {
                ListFiles(service, ref pageToken);

            } while (pageToken != null);

            textBox1.Text += "Upload file thành công.";
       
        }
    } 
}

DOWNLOAD SOURCE

 

Bonus:

using System;  
using System.IO;  
using System.Threading;  
using System.Threading.Tasks;  
using Google;  
using Google.Apis.Auth.OAuth2;  
using Google.Apis.Download;  
using Google.Apis.Drive.v3;  
using Google.Apis.Drive.v3.Data;  
using Google.Apis.Logging;  
using Google.Apis.Services;  
using Google.Apis.Upload;  
using Google.Apis.Util.Store;  
  
namespace ConsoleApplication6  
{  
    /// 
  
    /// A sample for the Drive API. This samples demonstrates resumable media upload and media download.  
    /// See https://developers.google.com/drive/ for more details regarding the Drive API.  
    ///   
    ///  
  
    class Program  
    {  
        static string ApplicationName = "Drive API .NET Quickstart";  
  
        static Program()  
        {  
            // initialize the log instance  
            Logger = ApplicationContext.Logger.ForType>();  
        }  
 
        #region Consts  
  
        private const int KB = 0x400;  
        private const int DownloadChunkSize = 256 * KB;  
  
        // CHANGE THIS with full path to the file you want to upload  
        //private const string UploadFileName = @"FILE_TO_UPLOAD";  
        private const string UploadFileName = @"cover.pdf";  
          
        // CHANGE THIS with a download directory  
        //private const string DownloadDirectoryName = @"DIRECTORY_FOR_DOWNLOADING";  
        private const string DownloadDirectoryName = @"C:	emp";  
  
        // CHANGE THIS if you upload a file type other than a jpg  
        private const string ContentType = @"application/pdf";  
 
        #endregion  
  
        /// 
The logger instance.  
        private static readonly ILogger Logger;  
  
        /// 
The Drive API scopes.  
        private static readonly string[] Scopes = new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive };  
  
        /// 
  
        /// The file which was uploaded. We will use its download Url to download it using our media downloader object.  
        ///   
        private static Google.Apis.Drive.v3.Data.File uploadedFile;  
  
        static void Main(string[] args)  
        {  
            Console.WriteLine("Google Drive API Sample");  
  
            try  
            {  
  
                new Program().Run().Wait();  
            }  
            catch (AggregateException ex)  
            {  
                foreach (var e in ex.InnerExceptions)  
                {  
                    Console.WriteLine("ERROR: " + e.Message);  
                }  
            }  
  
            Console.WriteLine("Press any key to continue...");  
            //Console.ReadKey();  
            Console.Read();  
        }  
  
        private async Task Run()  
        {  
            UserCredential credential;  
  
            using (var stream =  
              new FileStream("client_secret.json", FileMode.Open, FileAccess.ReadWrite))  
            {  
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);  
  
                credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");  
  
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(  
                  GoogleClientSecrets.Load(stream).Secrets,  
                  Scopes,  
                  "MyKeyName",  
                  CancellationToken.None,  
                  new FileDataStore(credPath, true)).Result;  
                Console.WriteLine("Credential file saved to: " + credPath);  
            }  
  
            // Create Drive API service.  
            var service = new DriveService(new BaseClientService.Initializer()  
            {  
                HttpClientInitializer = credential,  
                ApplicationName = ApplicationName  
            });  
              
            await UploadFileAsync(service);  
  
            // uploaded succeeded  
            Console.WriteLine(""{0}" was uploaded successfully", uploadedFile.Name);  
            await DownloadFile(service, uploadedFile.WebContentLink);  
        }  
  
        /// 
Uploads file asynchronously.  
        private Task UploadFileAsync(DriveService service)  
        {  
            var title = UploadFileName;  
            if (title.LastIndexOf('\') != -1)  
            {  
                title = title.Substring(title.LastIndexOf('\') + 1);  
            }  
  
            var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open,  
            System.IO.FileAccess.Read);  
  
            var insert = service.Files.Create(new Google.Apis.Drive.v3.Data.File { Name = title }, uploadStream, ContentType);  
  
            insert.ChunkSize = Google.Apis.Drive.v3.FilesResource.CreateMediaUpload.MinimumChunkSize * 2;  
            insert.ProgressChanged += Upload_ProgressChanged;  
            insert.ResponseReceived += Upload_ResponseReceived;  
  
            var task = insert.UploadAsync();  
  
            task.ContinueWith(t =>  
            {  
                // NotOnRanToCompletion - this code will be called if the upload fails  
                Console.WriteLine("Upload Filed. " + t.Exception);  
            }, TaskContinuationOptions.NotOnRanToCompletion);  
            task.ContinueWith(t =>  
            {  
                Logger.Debug("Closing the stream");  
                uploadStream.Dispose();  
                Logger.Debug("The stream was closed");  
            });  
  
            return task;  
        }  
  
        /// 
Downloads the media from the given URL.  
        private async Task DownloadFile(DriveService service, string url)  
        {  
            var downloader = new MediaDownloader(service);  
            downloader.ChunkSize = DownloadChunkSize;  
            // add a delegate for the progress changed event for writing to console on changes  
            downloader.ProgressChanged += Download_ProgressChanged;  
              
            var fileName = DownloadDirectoryName + @"cover.pdf";  
            using (var fileStream = new System.IO.FileStream(fileName,  
            System.IO.FileMode.Create, System.IO.FileAccess.Write))  
            {  
                var progress = await downloader.DownloadAsync(url, fileStream);  
                if (progress.Status == DownloadStatus.Completed)  
                {  
                    Console.WriteLine(fileName + " was downloaded successfully");  
                }  
                else  
                {  
                    Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",  
                    fileName, progress.BytesDownloaded);  
                }  
            }  
        }  
  
        /// 
Deletes the given file from drive (not the file system).  
        private async Task DeleteFile(DriveService service, Google.Apis.Drive.v3.Data.File file)  
        {  
            Console.WriteLine("Deleting file '{0}'...", file.Id);  
  
            await service.Files.Delete(file.Id).ExecuteAsync();  
            Console.WriteLine("File was deleted successfully");  
  
        }  
 
        #region Progress and Response changes  
  
        static void Download_ProgressChanged(IDownloadProgress progress)  
        {  
            Console.WriteLine(progress.Status + " " + progress.BytesDownloaded);  
        }  
  
        static void Upload_ProgressChanged(IUploadProgress progress)  
        {  
            Console.WriteLine(progress.Status + " " + progress.BytesSent);  
        }  
  
        static void Upload_ResponseReceived(Google.Apis.Drive.v3.Data.File file)  
        {  
            uploadedFile = file;  
        }  
 
        #endregion  
    }  
  
}  

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn upload multifile lên google drive Api  csharp
Đăng bởi: Thảo Meo - Lượt xem: 28778 22:36:15, 23/07/2017DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.