Exemple #1
0
        public async Task <JSON_Uploadedfile> Upload(object FileToUpload, Utilitiez.UploadTypes UploadType, string DestinationFolderPath, string FileName, bool UseFilename, bool OverwriteIfExists, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            //'FileName.Validation()
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                var progressHandler = new ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                using (HtpClient localHtpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage       HtpReqMessage      = new HttpRequestMessage(HttpMethod.Post, new pUri("upload?" + string.Format("path={0}", DestinationFolderPath.Trim('/'))));
                    MultipartFormDataContent MultipartsformData = new MultipartFormDataContent();
                    HttpContent strContent = null;
                    switch (UploadType)
                    {
                    case Utilitiez.UploadTypes.FilePath:
                        strContent = new StreamContent(new System.IO.FileStream(Convert.ToString(FileToUpload), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case Utilitiez.UploadTypes.Stream:
                        strContent = new StreamContent((System.IO.Stream)FileToUpload);
                        break;

                    case Utilitiez.UploadTypes.BytesArry:
                        strContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUpload));
                        break;
                    }

                    MultipartsformData.Add(new StringContent(UseFilename.ToString()), "use_filename");
                    MultipartsformData.Add(new StringContent(OverwriteIfExists.ToString()), "overwrite");
                    MultipartsformData.Add(strContent, "Image", FileName.Trim('/'));
                    HtpReqMessage.Content = MultipartsformData;
                    //'''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHtpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        token.ThrowIfCancellationRequested();
                        if (ResPonse.StatusCode == HttpStatusCode.OK)
                        {
                            ReportCls.Report(new ReportStatus {
                                Finished = true, TextStatus = string.Format("[{0}] Uploaded successfully", FileName)
                            });
                            return(JsonConvert.DeserializeObject <JSON_Uploadedfile>(JObject.Parse(result).SelectToken("uploadedFiles[*]").ToString(), JSONhandler));
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus {
                                Finished = true, TextStatus = string.Format("The request returned with HTTP status code {0}", JObject.Parse(result).SelectToken("message").ToString())
                            });
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new Image4ioException(ex.Message, 1001);
                }
                return(null);
            }
        }
Exemple #2
0
        public async Task <string> Upload(object FileToUpload, Utilitiez.UploadTypes UploadType, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            var uploadUrl = await GetUploaadUrl(FileName, UptoboxSDK.MimeMapping.GetMimeMapping(FileName));

            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                var progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                // '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                using (HtpClient localHttpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage HtpReqMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(uploadUrl.upload_url));
                    var           MultipartsformData = new MultipartFormDataContent();
                    StreamContent streamContent      = null;
                    // streamContent.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue(Web.MimeMapping.GetMimeMapping(FileName))
                    switch (UploadType)
                    {
                    case Utilitiez.UploadTypes.FilePath:
                        streamContent = new StreamContent(new System.IO.FileStream(FileToUpload.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case Utilitiez.UploadTypes.Stream:
                        streamContent = new StreamContent((System.IO.Stream)FileToUpload);
                        break;

                    case Utilitiez.UploadTypes.BytesArry:
                        streamContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUpload));
                        break;
                    }

                    // streamContent.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") With {.Name = """files[]""", .FileName = """" + FileName + """"}
                    // streamContent.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream")
                    MultipartsformData.Add(streamContent, "file", FileName);
                    HtpReqMessage.Content = MultipartsformData;
                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        token.ThrowIfCancellationRequested();
                        if (ResPonse.StatusCode == HttpStatusCode.NoContent)
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"[{FileName}] Uploaded successfully"
                            });
                            return(uploadUrl.file_url);
                        }
                        else
                        {
                            string result = await ResPonse.Content.ReadAsStringAsync();

                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"The request returned with HTTP status code {ResPonse.ReasonPhrase}"
                            });
                            ShowError(result);
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new PushbulletException(ex.Message, 1001);
                }
                return(null);
            }
        }