Esempio n. 1
0
        public string UploadFile(string fileName)
        {
            try
            {
                Logger.Info($"Uploading file {fileName}");

                // https://developers.google.com/photos/library/guides/upload-media

                var url = "https://photoslibrary.googleapis.com/v1/uploads";

                var request = (HttpWebRequest)WebRequest.Create(url);

                request.Method      = "POST";
                request.ContentType = "application/octet-stream";

                var fNameValidForHeader = GAPICommunication.NormalizeStringForUrl(Path.GetFileNameWithoutExtension(fileName)) +
                                          "." + GAPICommunication.NormalizeStringForUrl(Path.GetExtension(fileName));
                request.Headers["X-Goog-Upload-File-Name"] = fNameValidForHeader; // non ascii characters cause "System.ArgumentException: Specified value has invalid CRLF characters."
                request.Headers["X-Goog-Upload-Protocol"]  = "raw";

                // fill request stream buffer with file
                var    bytesRead = 0;
                byte[] buffer    = new byte[16384];

                string responseString;

                using (var requestStream = request.GetRequestStream())
                {
                    using (var fs = System.IO.File.OpenRead(fileName))
                    {
                        while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            requestStream.Write(buffer, 0, bytesRead);
                        }
                    }

                    Logger.Debug("Posting file data");

                    responseString = GAPICommunication.SendRequest(request, this);
                }

                return(responseString);
            } catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }