protected void btnUpload_Click(object sender, EventArgs e)
    {
      if (Session["AccessToken"] == null)
      {
        Response.Write("Error. Access token not found.<br /><a href=\"/\">Try again</a>.");
        pnlUpload.Visible = false;
        return;
      }

      // help: https://developers.google.com/drive/v2/reference/files/insert

      var token = Session["AccessToken"].ToString();

      try
      {
        /*
        // simple upload
        var result = OAuthUtility.Post
        (
          "https://www.googleapis.com/upload/drive/v2/files",
          new HttpParameterCollection
          { 
            { "uploadType", "media" },
            { FileUpload1.PostedFile } 
          },
          new HttpAuthorization(AuthorizationType.Bearer, token)
        );
        */

        var parameters = new HttpParameterCollection();
        parameters.Add("uploadType", "multipart");
        parameters.AddContent("application/json", new { title = FileUpload1.FileName });
        parameters.AddContent(FileUpload1.PostedFile);

        var result = OAuthUtility.Post
        (
          "https://www.googleapis.com/upload/drive/v2/files",
          parameters, 
          authorization: new HttpAuthorization(AuthorizationType.Bearer, token),
          contentType: "multipart/related"
        );

        // ok
        hlResult.NavigateUrl = result["webContentLink"].ToString();
        hlResult.Text = hlResult.NavigateUrl;
          
        pnlSuccess.Visible = true;
        pnlUpload.Visible = false;
      }
      catch (Exception ex)
      {
        Response.Write(ex.Message);
      }
    }
示例#2
0
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (Session["AccessToken"] == null)
            {
                Response.Write("Error. Access token not found.<br /><a href=\"/\">Try again</a>.");
                pnlUpload.Visible = false;
                return;
            }

            // help: https://developers.google.com/drive/v2/reference/files/insert

            var token = Session["AccessToken"].ToString();

            try
            {
                /*
                 * // simple upload
                 * var result = OAuthUtility.Post
                 * (
                 * "https://www.googleapis.com/upload/drive/v2/files",
                 * new HttpParameterCollection
                 * {
                 *  { "uploadType", "media" },
                 *  { FileUpload1.PostedFile }
                 * },
                 * new HttpAuthorization(AuthorizationType.Bearer, token)
                 * );
                 */

                var parameters = new HttpParameterCollection();
                parameters.Add("uploadType", "multipart");
                parameters.AddContent("application/json", new { title = FileUpload1.FileName });
                parameters.AddContent(FileUpload1.PostedFile);

                var result = OAuthUtility.Post
                             (
                    "https://www.googleapis.com/upload/drive/v2/files",
                    parameters,
                    authorization: new HttpAuthorization(AuthorizationType.Bearer, token),
                    contentType: "multipart/related"
                             );

                // ok
                hlResult.NavigateUrl = result["webContentLink"].ToString();
                hlResult.Text        = hlResult.NavigateUrl;

                pnlSuccess.Visible = true;
                pnlUpload.Visible  = false;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
示例#3
0
        private void button2_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;

            if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            object parents = null;

            if (!String.IsNullOrEmpty(this.CurrentFolderId))
            {
                parents = new object[] { new { id = this.CurrentFolderId } };
            }

            UniValue properties = UniValue.Create
                                  (
                new
            {
                title   = Path.GetFileName(openFileDialog1.FileName),
                parents = parents
            }
                                  );

            var file = openFileDialog1.OpenFile();

            this.CurrentFileLength = file.Length;

            var parameters = new HttpParameterCollection();

            parameters.Add("uploadType", "multipart");
            parameters.AddContent("application/json", properties.ToString());
            parameters.AddContent("application/octet-stream", file);

            OAuthUtility.PostAsync
            (
                "https://www.googleapis.com/upload/drive/v2/files",
                parameters,
                authorization: new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken),
                contentType: "multipart/related",
                // handler of result
                callback: Upload_Result,
                // handler of uploading
                streamWriteCallback: Upload_Processing
            );
        }
示例#4
0
        private void button1_Click(object sender, EventArgs e)
        {
            // help: https://developers.google.com/drive/v2/reference/files/insert

            object parents = null;

            if (!String.IsNullOrEmpty(this.CurrentFolderId))
            {
                parents = new object[] { new { id = this.CurrentFolderId } };
            }

            UniValue content = UniValue.Create
                               (
                new
            {
                mimeType = "application/vnd.google-apps.folder",
                title    = textBox1.Text,
                parents  = parents
            }
                               );

            var parameters = new HttpParameterCollection();

            parameters.Encoding = Encoding.UTF8;
            parameters.Add("uploadType", "multipart");
            parameters.AddContent("application/json", content.ToString());

            OAuthUtility.PostAsync
            (
                "https://www.googleapis.com/upload/drive/v2/files",
                parameters: parameters,
                authorization: new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken),
                contentType: "multipart/related",
                callback: CreateFolder_Result
            );
        }
示例#5
0
        /// <summary>
        /// https://dev.twitter.com/rest/reference/post/media/upload-append
        /// </summary>
        /// <param name="path">File path.</param>
        /// <param name="media_id">Media id.</param>
        /// <param name="chunk">Chunk. Default: 0.</param>
        /// <param name="uploadingCallback">Uploading callback.</param>
        private static async Task <RequestResult> MeadiaUploadAppend(string path, string media_id, int chunk, MeadiaUploadEventHandler uploadingCallback)
        {
            var  file      = new FileInfo(path);
            bool isUploded = false;

            byte[] media = null;

            if (chunk > 0)
            {
                // multiple chunks
                using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Inheritable))
                    using (var reader = new BinaryReader(stream))
                    {
                        stream.Position = (TwitterApi.MediaUploadChunkSize * chunk);
                        media           = reader.ReadBytes(TwitterApi.MediaUploadChunkSize);
                        isUploded       = (stream.Position == stream.Length);
                    }
            }
            else
            {
                if (file.Length <= TwitterApi.MediaUploadChunkSize)
                {
                    // one chunk
                    using (var reader = new BinaryReader(file.Open(FileMode.Open, FileAccess.Read, FileShare.Inheritable)))
                    {
                        media     = reader.ReadBytes(Convert.ToInt32(file.Length));
                        isUploded = true;
                    }
                }
                else
                {
                    // multiple chunks
                    using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Inheritable))
                        using (var reader = new BinaryReader(stream))
                        {
                            media     = reader.ReadBytes(TwitterApi.MediaUploadChunkSize);
                            isUploded = (stream.Position == stream.Length);
                        }
                }
            }

            var parameters = new HttpParameterCollection();

            parameters.AddFormParameter("command", "APPEND");
            parameters.AddFormParameter("media_id", media_id);
            parameters.AddFormParameter("segment_index", chunk.ToString());
            parameters.Add("media", Path.GetFileName(path), media);

            var t = Task.Run <RequestResult>(() =>
            {
                return(OAuthUtility.Post
                       (
                           "https://upload.twitter.com/1.1/media/upload.json",
                           parameters: parameters,
                           authorization: TwitterApi.GetAuth(),
                           contentType: "multipart/form-data",
                           streamWriteCallback: (object s, StreamWriteEventArgs e) =>
                {
                    int progressPercentage = 0;
                    long totalUploaded = 0;

                    if (chunk > 0)
                    {
                        totalUploaded = TwitterApi.MediaUploadChunkSize * chunk;
                    }

                    totalUploaded += e.TotalBytesWritten;

                    progressPercentage = Convert.ToInt32((totalUploaded * 100) / file.Length);

                    uploadingCallback?.Invoke(s, new ProgressChangedEventArgs(progressPercentage, null));
                }
                       ));
            });

            var result = await t;

            if (!result.IsSuccessfully)
            {
                // error
                return(result);
            }

            if (file.Length > TwitterApi.MediaUploadChunkSize && !isUploded)
            {
                // next chunk
                return(await TwitterApi.MeadiaUploadAppend(path, media_id, chunk + 1, uploadingCallback));
            }
            else
            {
                // finalize
                return(await TwitterApi.MeadiaUploadFinalize(path, media_id));
            }
        }
示例#6
0
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (Session["AccessToken"] == null)
            {
                Response.Write("Error. Access token not found.<br /><a href=\"/\">Try again</a>.");
                pnlUpload.Visible = false;
                return;
            }

            // help: https://developers.google.com/drive/v2/reference/files/insert

            var token    = Session["AccessToken"].ToString();
            var filePath = Server.MapPath(String.Format("~/Temp/{0}.tmp", Guid.NewGuid()));

            try
            {
                /*
                 * // simple upload
                 * var result = OAuthUtility.Post
                 * (
                 * "https://www.googleapis.com/upload/drive/v2/files",
                 * new HttpParameterCollection
                 * {
                 *  { "uploadType", "media" },
                 *  { FileUpload1.PostedFile }
                 * },
                 * new HttpAuthorization(AuthorizationType.Bearer, token)
                 * );
                 */

                // save file
                if (!Directory.Exists(Server.MapPath("~/Temp")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Temp"));
                }

                using (var file = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.Inheritable))
                    using (var writer = new BinaryWriter(file))
                    {
                        using (var reader = new BinaryReader(FileUpload1.PostedFile.InputStream))
                        {
                            byte[] buffer    = new byte[4096];
                            int    readBytes = 0;

                            while ((readBytes = reader.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                writer.Write(buffer, 0, readBytes);
                            }
                        }
                    }

                var fileToSend = File.OpenRead(filePath);

                // send saved file
                var parameters = new HttpParameterCollection();
                parameters.Add("uploadType", "multipart");
                parameters.AddContent("application/json", new { title = FileUpload1.FileName });
                parameters.AddContent
                (
                    FileUpload1.PostedFile.ContentType ?? "application/octet-stream",
                    fileToSend
                );

                var result = OAuthUtility.Post
                             (
                    "https://www.googleapis.com/upload/drive/v2/files",
                    parameters,
                    authorization: new HttpAuthorization(AuthorizationType.Bearer, token),
                    contentType: "multipart/related"
                             );

                fileToSend.Close();

                // ok
                hlResult.NavigateUrl = result["webContentLink"].ToString();
                hlResult.Text        = hlResult.NavigateUrl;

                pnlSuccess.Visible = true;
                pnlUpload.Visible  = false;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                // remove temp file
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
        }