02/10/2018, 00:59

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

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. - Đầ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 ...

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.

- Đầ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<string>
            {
                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

Tags: download fileghi fileđọc fileftpserver
0