Exemple #1
0
        public static void UploadFileAsync(string fileLocation, string submitAct, UploadProgressChangedEventHandler uploadHandler, UploadFileCompletedEventHandler completedHandler, string programid = null)
        {
            try
            {
                using (ByteGuardWebClient byteguardWebClient = new ByteGuardWebClient())
                {
                    byteguardWebClient.Headers.Add("Content-Type", "binary/octet-stream");
                    byteguardWebClient.CookieJar = CookieContainer;

                    byteguardWebClient.UploadProgressChanged += uploadHandler;
                    byteguardWebClient.UploadFileCompleted   += completedHandler;

                    Uri postUri =
                        new Uri(
                            String.Format("{0}files/upload.php?type={1}&pid={2}",
                                          Variables.ByteGuardHost, submitAct, programid));

                    lock (LockObject)
                    {
                        byteguardWebClient.UploadFileAsync(postUri, "POST", fileLocation);
                    }
                }
            }
            catch
            {
                Variables.Containers.Main.SetStatus("Failed to upload program image, please try again shortly.", 1);
            }
        }
        public async Task<string> UploadBytesAsync(
            byte[] imageBytes,
            UploadProgressChangedEventHandler progress = null,
            UploadValuesCompletedEventHandler completed = null)
        {
            using (var w = new WebClient())
            {
                try
                {
                    const string clientId = "68a0074c7783fd4";
                    w.Headers.Add("Authorization", "Client-ID " + clientId);
                    var values = new NameValueCollection
                    {
                        {"image", Convert.ToBase64String(imageBytes)}
                    };

                    if (progress != null) w.UploadProgressChanged += progress;
                    if (completed != null) w.UploadValuesCompleted += completed;

                    var response = await w.UploadValuesTaskAsync("https://api.imgur.com/3/upload.json", values);
                    var json = Encoding.UTF8.GetString(response);
                    dynamic model = JsonConvert.DeserializeObject(json);
                    return ((bool)model.success) ? (string)model.data.link : (string)model.data.error;
                }
                catch (Exception e)
                {
                    return e.Message;
                }
                finally
                {
                    if (progress != null) w.UploadProgressChanged -= progress;
                    if (completed != null) w.UploadValuesCompleted -= completed;
                }
            }
        }
        public async Task UploadArbitraryByteArray()
        {
            var tsc = new TaskCompletionSource <bool>();

            var name = $"{Guid.NewGuid()}.bin";
            UploadProgressChangedEventHandler onProgress = (sender, args) =>
            {
                tsc.TrySetResult(true);
            };

            await bucket.Upload(new Byte[] { 0x0, 0x0, 0x0 }, name, null, onProgress);

            var list = await bucket.List();

            var existing = list.Find(item => item.Name == name);

            Assert.IsNotNull(existing);

            var sentProgressEvent = await tsc.Task;

            Assert.IsTrue(sentProgressEvent);

            await bucket.Remove(new List <string> {
                name
            });
        }
Exemple #4
0
        /// <summary>
        /// Upload the specified file to the MediaCrush (or other) server.
        /// </summary>
        /// <param name="file">The file to upload</param>
        /// <returns>Returns one <see cref="FileUploadResult"/></returns>
        /// <remarks>API Doc Url: https://github.com/MediaCrush/MediaCrush/blob/master/docs/api.md#apiuploadfile </remarks>
        public static void UploadFileAsync(string file, UploadProgressChangedEventHandler progressHandler, Action <FileUploadResult> callback)
        {
            if (!File.Exists(file))
            {
                throw new FileNotFoundException("Specified file doesn't exist", file);
            }

            Upload(BaseApiUrl + FileUploadApiUrl, file, progressHandler, (s, e) =>
            {
                var json = Encoding.UTF8.GetString(e.Result);
                FileUploadResult result = JsonConvert.DeserializeObject <FileUploadResult>(json);

                // Because the hash is the key of the SharpCrushMediaFile (I have no idea why), dynamic objects are needed //
                var dynamicObject = JsonConvert.DeserializeObject <dynamic>(json);

                // Sometimes it returns a somewhat malformed array. //
                // https://github.com/MediaCrush/MediaCrush/issues/356 //
                if (dynamicObject[result.FileHash] is JArray)
                {
                    // We going to have to get media files a different way //
                    var mediaFile    = GetFileInfo(result.FileHash);
                    result.MediaFile = mediaFile;
                }

                if (dynamicObject[result.FileHash] is JObject)
                {
                    // This is the expected/faster way //
                    var jObject      = (JObject)dynamicObject[result.FileHash];
                    result.MediaFile = jObject.ToObject <SharpCrushMediaFile>();
                }

                callback(result);
            });
        }
        public async Task UploadFile()
        {
            var tsc = new TaskCompletionSource <bool>();

            var asset     = "supabase-csharp.png";
            var name      = $"{Guid.NewGuid()}.png";
            var basePath  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:", "");
            var imagePath = Path.Combine(basePath, "Assets", asset);

            UploadProgressChangedEventHandler onProgress = (sender, args) =>
            {
                tsc.TrySetResult(true);
            };

            await bucket.Upload(imagePath, name, null, onProgress);

            var list = await bucket.List();

            var existing = list.Find(item => item.Name == name);

            Assert.IsNotNull(existing);

            var sentProgressEvent = await tsc.Task;

            Assert.IsTrue(sentProgressEvent);

            await bucket.Remove(new List <string> {
                name
            });
        }
Exemple #6
0
 public void UploadFileAsync(Uri uri, string filePath, UploadProgressChangedEventHandler progressHandler = null, UploadFileCompletedEventHandler completedHandler = null)
 {
     lhLoom.RunAsync(() =>
     {
         using (WebClient client = new WebClient())
         {
             client.UploadProgressChanged += (sender, e) => {
                 lhLoom.RunMain(() =>
                 {
                     if (progressHandler != null)
                     {
                         progressHandler(sender, e);
                     }
                 });
             };
             client.UploadFileCompleted += (sender, e) => {
                 lhLoom.RunMain(() =>
                 {
                     if (completedHandler != null)
                     {
                         completedHandler(sender, e);
                     }
                 });
             };
             client.UploadFileAsync(uri, filePath);
         }
     });
 }
        /// <summary>
        ///     Checks if file exists and uploads file. This along with parsing the output of the JSON response.
        /// </summary>
        /// <param name="fileLocation"> The specified path to the file to be uploaded. </param>
        /// <param name="handler"> A progress changed handler that can monitor the progress of the upload. </param>
        public AnonFile UploadFileAsync(string fileLocation, UploadProgressChangedEventHandler handler = null)
        {
            string         response   = null;
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            if (!File.Exists(fileLocation))
            {
                throw new AnonFileException($"Invalid file path at {fileLocation}");
            }

            _client.UploadFileAsync(new Uri("https://api.anonfile.com/upload"), fileLocation);


            if (handler != null)
            {
                _client.UploadProgressChanged += handler;
            }

            _client.UploadFileCompleted += (self, e) =>
            {
                waitHandle.Set();
                response = Encoding.Default.GetString(e.Result);
            };

            waitHandle.WaitOne();
            waitHandle.Dispose();

            return(response != null?ParseOutput(response) : throw new AnonFileException("Failed to grab AnonFile's server response to the upload event!"));;
        }
        /// <summary>
        /// Create an instance of the DatabaseAutomationRunner window
        /// </summary>
        public DatabaseAutomationRunner(ModpackSettings modpackSettings, Logfiles logfile) : base(modpackSettings, logfile)
        {
            InitializeComponent();
            DownloadProgressChanged = WebClient_DownloadProgressChanged;
            DownloadDataCompleted   = WebClient_DownloadDataComplted;
            DownloadFileCompleted   = WebClient_TransferFileCompleted;
            UploadFileCompleted     = WebClient_UploadFileCompleted;
            UploadProgressChanged   = WebClient_UploadProgressChanged;
            RelhaxProgressChanged   = RelhaxProgressReport_ProgressChanged;
            ProgressChanged         = GenericProgressChanged;
            Settings = AutomationSettings;

            //https://stackoverflow.com/questions/7712137/array-containing-methods
            settingsMethods = new Action[]
            {
                () => OpenLogWindowOnStartupSetting_Click(null, null),
                () => BigmodsUsernameSetting_TextChanged(null, null),
                () => BigmodsPasswordSetting_TextChanged(null, null),
                () => DumpParsedMacrosPerSequenceRunSetting_Click(null, null),
                () => DumpEnvironmentVariablesAtSequenceStartSetting_Click(null, null),
                () => SuppressDebugMessagesSetting_Click(null, null),
                () => AutomamtionDatabaseSelectedBranchSetting_TextChanged(null, null),
                () => SelectDBSaveLocationSetting_TextChanged(null, null),
                () => UseLocalRunnerDatabaseSetting_Click(null, null),
                () => LocalRunnerDatabaseRootSetting_TextChanged(null, null),
                () => SelectWoTInstallLocationSetting_TextChanged(null, null)
            };
        }
 public void CompleteDeposit(string endpoint, UploadDataCompletedEventHandler completed, UploadProgressChangedEventHandler changed)
 {
     this.Headers["In-Progress"] = "false";
     this.UploadDataCompleted += completed;
     this.UploadProgressChanged += changed;
     UploadDataAsync(new Uri(endpoint), "POST", new byte[0]);
 }
Exemple #10
0
        public static void UploadImage(string sLocalFile,
                                       UploadFileCompletedEventHandler Client_UploadFileCompleted,
                                       UploadProgressChangedEventHandler Client_UploadProgressChanged,
                                       bool HD = false)
        {
            if (string.IsNullOrEmpty(sLocalFile))
            {
                Console.WriteLine("ImageUploadService: File empty");
                return;
            }
            //string sLocalCache = Path.Combine(Globals.AppDataPath, Helper.GUID() + ".jpg");
            System.Net.WebClient Client = new System.Net.WebClient();
            // Client.Credentials = CredentialCache.DefaultCredentials;

            Image bmp = Bitmap.FromFile(sLocalFile);

            int size = 800;

            if (HD == true)
            {
                size = 1024;
            }

            Image bmp2 = ImageTools.ScaleImageProportional(bmp, size, size);

            FileInfo fi        = new FileInfo(sLocalFile);
            string   extension = fi.Extension;

            string tempname = Helper.HashString(DateTime.Now.ToString()) + extension;
            string TempName = Path.Combine(MFileSystem.AppDataPath, tempname);

            if (File.Exists(TempName))
            {
                File.Delete(TempName);
            }

            bmp2.Save(TempName);

            bmp.Dispose();
            bmp2.Dispose();

            Client.Headers.Add("Content-Type", "binary/octet-stream");
            Client.Headers.Add("UserID:" + Globals.UserAccount.UserID);

            string CDNLocation = "";

            if (!string.IsNullOrEmpty(Globals.Network.ServerDomain))
            {
                CDNLocation = Globals.Network.ServerDomain;
            }
            else
            {
                CDNLocation = Globals.Network.ServerIP;
            }

            Client.UploadFileAsync(new Uri("http://" + CDNLocation + "/massive/fu/fu.php"), "POST", TempName);
            Client.UploadFileCompleted   += Client_UploadFileCompleted;
            Client.UploadProgressChanged += Client_UploadProgressChanged;
        }
Exemple #11
0
        private async void OnUploadToImgur(object sender, RoutedEventArgs e)
        {
            try
            {
                UploadProgressChangedEventHandler progress = (o, args) => TextEditor.Dispatcher.InvokeAsync(() =>
                {
                    if (_canceled)
                    {
                        ((WebClient)o).CancelAsync();
                    }
                    var progressPercentage = (int)((args.BytesSent / (double)args.TotalBytesToSend) * 100);
                    ProgressBar.Value      = progressPercentage;
                    if (progressPercentage == 100)
                    {
                        ProgressBar.IsIndeterminate = true;
                    }
                });

                UploadValuesCompletedEventHandler completed = (o, args) => { if (_canceled)
                                                                             {
                                                                                 ((WebClient)o).CancelAsync();
                                                                             }
                };

                string name;
                byte[] image;

                if (UseClipboardImage)
                {
                    name  = "clipboard";
                    image = Images.ClipboardDibToBitmapSource().ToPngArray();
                }
                else
                {
                    var path = DroppedFilePath();
                    name  = Path.GetFileNameWithoutExtension(path);
                    image = File.ReadAllBytes(path);
                }

                Uploading = true;
                var link = await new ImageUploadImgur().UploadBytesAsync(image, progress, completed);
                Close();

                if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
                {
                    InsertImageTag(TextEditor, DragEventArgs, link, name);
                }
                else
                {
                    Utility.Alert(link);
                }
            }
            catch (Exception ex)
            {
                Close();
                Utility.Alert(ex.Message);
            }
        }
Exemple #12
0
        protected virtual void OnUploadProgressChanged(UploadProgressChangedEventArgs e)
        {
            UploadProgressChangedEventHandler handler = UploadProgressChanged;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Exemple #13
0
        /// <summary>
        /// This event is raised each time upload makes progress.
        /// </summary>
        private void Gett_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            UploadProgressChangedEventHandler copyUploadProgressChanged = UploadProgressChanged;

            if (copyUploadProgressChanged != null)
            {
                copyUploadProgressChanged(this, e);
            }
        }
Exemple #14
0
        /// <summary>
        /// 上传文件并且使用自定义字段。注意,boundary在请求体中和header中差了“--”两个横线,如果不对应一定会上传失败!
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        public static async Task <string> UploadImgAsync(String line, UploadProgressChangedEventHandler uploadProgressChanged)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            webClient.Headers.Add("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary);
            //   webClient.Headers.Add("Referer", "https://pixhost.org/");
            webClient.Headers.Add("Accept", "application/json");

            webClient.UploadProgressChanged += uploadProgressChanged;


            byte[] HeaderByte = Encoding.UTF8.GetBytes(ByteHelper.CreateHeadInfo(boundary, "img", "") + string.Format(";filename=\"{0}\"\r\nContent-Type: image/jpeg\r\n\r\n", Path.GetFileName(line)));
            byte[] File       = ByteHelper.StreamToBytes(System.IO.File.OpenRead(line));//读取文件
            byte[] EndByte    = Encoding.UTF8.GetBytes("\r\n" + ByteHelper.CreateHeadInfo(boundary, "content_type", "\r\n\r\n0") + "\r\n--" + boundary + "--");

            List <Byte[]> listcat = new List <byte[]>();

            listcat.Add(HeaderByte);
            listcat.Add(File);
            /*如需其他自定义字段,请自行定义然后添加到listcat中,下面的copybit会自动合并所有数据*/
            listcat.Add(EndByte);
            byte[] bytes = ByteHelper.MergeByte(listcat);



            String ImgUrl = "";

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    byte[] responseArray = await webClient.UploadDataTaskAsync(new Uri("https://api.pixhost.org/images"), "POST", bytes);

                    String Shtml = Encoding.UTF8.GetString(responseArray);

                    PixHostJson.Root AllJson = JsonConvert.DeserializeObject <PixHostJson.Root>(Shtml);

                    ImgUrl = AllJson.th_url.Replace("/thumbs/", "/images/").Replace("https://t", "https://img");
                    Console.WriteLine(ImgUrl);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                if (ImgUrl != "")
                {
                    break;
                }
                else
                {
                    Console.WriteLine("上传{0}未成功,第{1}次重试", line, i);
                }
            }

            return(ImgUrl);
        }
Exemple #15
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// uploadprogresschangedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this UploadProgressChangedEventHandler uploadprogresschangedeventhandler, Object sender, UploadProgressChangedEventArgs e, AsyncCallback callback)
        {
            if (uploadprogresschangedeventhandler == null)
            {
                throw new ArgumentNullException("uploadprogresschangedeventhandler");
            }

            return(uploadprogresschangedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Exemple #16
0
        private async void OnUploadToImgur(object sender, RoutedEventArgs e)
        {
            var name = "Clipboard";

            if (Image == null)
            {
                var files = DragEventArgs.Data.GetData(DataFormats.FileDrop) as string[];
                if (files == null)
                {
                    return;
                }
                var path = files[0];
                name = Path.GetFileNameWithoutExtension(path);
                try
                {
                    Image = File.ReadAllBytes(path);
                }
                catch (Exception ex)
                {
                    Close();
                    MessageBox.Show(Application.Current.MainWindow, ex.Message, App.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }

            UploadProgressChangedEventHandler progress = (o, args) => TextEditor.Dispatcher.InvokeAsync(() =>
            {
                if (_canceled)
                {
                    ((WebClient)o).CancelAsync();
                }
                var progressPercentage = (int)((args.BytesSent / (double)args.TotalBytesToSend) * 100);
                ProgressBar.Value      = progressPercentage;
                if (progressPercentage == 100)
                {
                    ProgressBar.IsIndeterminate = true;
                }
            });

            UploadValuesCompletedEventHandler completed = (o, args) => { if (_canceled)
                                                                         {
                                                                             ((WebClient)o).CancelAsync();
                                                                         }
            };

            var link = await new ImageUploadImgur().UploadBytesAsync(Image, progress, completed);

            Close();
            if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
            {
                InsertImageTag(TextEditor, DragEventArgs, link, name);
            }
            else
            {
                MessageBox.Show(Application.Current.MainWindow, link, App.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #17
0
        /// <summary>
        /// 上传文件并且使用自定义字段。注意,boundary在请求体中和header中差了“--”两个横线,如果不对应一定会上传失败!
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        public static async Task <string> UploadImgAsync(String line, UploadProgressChangedEventHandler uploadProgressChanged)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);

            webClient.Headers.Add("Referer", "https://upload.cc/index.html");
            webClient.UploadProgressChanged += uploadProgressChanged;

            String Header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"uploaded_file[]\"; filename=\"" + Path.GetFileName(line) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";

            byte[] HeaderByte = Encoding.UTF8.GetBytes(Header);
            byte[] File       = ByteHelper.StreamToBytes(System.IO.File.OpenRead(line));//读取文件
            byte[] EndByte    = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");

            List <Byte[]> listcat = new List <byte[]>();

            listcat.Add(HeaderByte);
            listcat.Add(File);
            /*如需其他自定义字段,请自行定义然后添加到listcat中,下面的copybit会自动合并所有数据*/
            listcat.Add(EndByte);
            byte[] bytes = ByteHelper.MergeByte(listcat);



            String ImgUrl = "";

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    byte[] responseArray = await webClient.UploadDataTaskAsync(new Uri("https://upload.cc/new_ui_upload.php"), "POST", bytes);

                    String Shtml = Encoding.UTF8.GetString(responseArray);

                    ImgUrl = Regex.Match(Shtml, "src=\"(.*?)\"").Value;
                    ImgUrl = Regex.Replace(ImgUrl, "src=\"|\"", "");
                    Console.WriteLine(ImgUrl);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                if (ImgUrl != "")
                {
                    break;
                }
                else
                {
                    Console.WriteLine("上传{0}未成功,第{1}次重试", line, i);
                }
            }

            return(ImgUrl);
        }
Exemple #18
0
 public void Upload(string cloudPath, string token, string clientPath, UploadProgressChangedEventHandler peh, TaskCompletionSource <bool> tcs)
 {
     using (var web = new WebClient())
     {
         web.Headers["Authorization"] = "Bearer " + token;
         web.UploadProgressChanged   += peh;
         web.UploadFileCompleted     += (sender, args) => Web_UploadFileCompleted(sender, tcs, args);
         web.UploadFileAsync(new Uri(string.Format("https://content.dropboxapi.com/1/files_put/auto/{0}", cloudPath)), "PUT", clientPath);
     }
 }
 public void Upload(string cloudPath, string token, string clientPath, UploadProgressChangedEventHandler peh, TaskCompletionSource <bool> tcs)
 {
     token = RefreshToken(token);
     using (var web = new WebClient())
     {
         web.Headers["Authorization"] = "Bearer " + token;
         web.UploadProgressChanged   += peh;
         web.UploadFileCompleted     += (sender, args) => Web_UploadFileCompleted(sender, tcs, args);
         web.UploadFileAsync(new Uri(string.Format("https://api.onedrive.com/v1.0/drive/special/approot:{0}:/content", cloudPath)), "PUT", clientPath);
     }
 }
Exemple #20
0
        public async Task <string> UploadBytesAsync(
            byte[] imageBytes,
            UploadProgressChangedEventHandler progress  = null,
            UploadValuesCompletedEventHandler completed = null)
        {
            using (var w = new WebClient())
            {
                try
                {
                    const string clientId = "68a0074c7783fd4";
                    w.Headers.Add("Authorization", "Client-ID " + clientId);
                    var values = new NameValueCollection
                    {
                        { "image", Convert.ToBase64String(imageBytes) }
                    };

                    if (progress != null)
                    {
                        w.UploadProgressChanged += progress;
                    }
                    if (completed != null)
                    {
                        w.UploadValuesCompleted += completed;
                    }

                    var response = await w.UploadValuesTaskAsync("https://api.imgur.com/3/upload.json", values);

                    var     json  = Encoding.UTF8.GetString(response);
                    dynamic model = JsonConvert.DeserializeObject(json);
                    return(((bool)model.success) ? (string)model.data.link : (string)model.data.error);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
                finally
                {
                    if (progress != null)
                    {
                        w.UploadProgressChanged -= progress;
                    }
                    if (completed != null)
                    {
                        w.UploadValuesCompleted -= completed;
                    }
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// 上传文件并且使用自定义字段。注意,boundary在请求体中和header中差了“--”两个横线,如果不对应一定会上传失败!
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        public static async Task<string> UploadImgAsync(String line,UploadProgressChangedEventHandler uploadProgressChanged) {

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);


            webClient.UploadProgressChanged += uploadProgressChanged;

            String Header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"smfile\"; filename=\"" + Path.GetFileName(line) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
            byte[] HeaderByte = Encoding.UTF8.GetBytes(Header);
            byte[] File =ByteHelper. StreamToBytes(System.IO.File.OpenRead(line));//读取文件
            byte[] EndByte = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");

            List<Byte[]> listcat = new List<byte[]>();
            listcat.Add(HeaderByte);
            listcat.Add(File);
            /*如需其他自定义字段,请自行定义然后添加到listcat中,下面的copybit会自动合并所有数据*/
            listcat.Add(EndByte);
            byte[] bytes = ByteHelper.MergeByte(listcat);




            String ImgUrl = "";
            for (int i = 0; i < 3; i++) {
                try
                {
             byte[] responseArray=  await webClient.UploadDataTaskAsync(new Uri("https://sm.ms/api/upload"),"POST", bytes);
              
                    String Shtml = Encoding.UTF8.GetString(responseArray);
                   ILoliJson.Root AllJson = JsonConvert.DeserializeObject<ILoliJson.Root>(Shtml);
                    ImgUrl = AllJson.data.url;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                if (ImgUrl != "")
                    break;
                else {
                    Console.WriteLine("上传{0}未成功,第{1}次重试",line,i);
                }
            }
         
            return ImgUrl;
        }
Exemple #22
0
 private static void Upload(string url, string filePath, UploadProgressChangedEventHandler progressHandler, UploadFileCompletedEventHandler completeHandler)
 {
     using (var client = new WebClient())
     {
         try
         {
             client.UploadProgressChanged += progressHandler;
             client.UploadFileCompleted   += completeHandler;
             client.UploadFileAsync(new Uri(url), filePath);
         }
         catch (WebException ex)
         {
             if (ex.Response != null)
             {
                 new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
             }
         }
     }
 }
 public void DeleteResource(string endpoint, UploadDataCompletedEventHandler completed, UploadProgressChangedEventHandler changed)
 {
     this.UploadDataCompleted   += completed;
     this.UploadProgressChanged += changed;
     UploadDataAsync(new Uri(endpoint), "DELETE", new byte[0]);
 }
Exemple #24
0
        public async Task <T> RequestAsync <T>(string url, string method = Get, T data = null, IAuthSerializer auth = null, DownloadProgressChangedEventHandler progressGet = null, UploadProgressChangedEventHandler progressPost = null) where T : class
        {
            string response;
            var    json = new JsonParser();

            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Encoding = Encoding.UTF8;
                try
                {
                    if (auth != null)
                    {
                        Auth(client, auth);
                    }

                    if (method == Post)
                    {
                        client.UploadProgressChanged += progressPost;
                        var param = json.ParseObjToStr(data);
                        response = await client.UploadStringTaskAsync(new Uri(url), param);
                    }
                    else
                    {
                        client.DownloadProgressChanged += progressGet;
                        client.QueryString              = SetParameters(data);
                        response = await client.DownloadStringTaskAsync(url);
                    }
                }
                catch (WebException ex)
                {
                    dynamic servResp = ex.Response;
                    if (ex.Response == null)
                    {
                        response = "{\"detail\":[\"Невозможно подключиться к серверу\"]}";
                    }
                    else
                    {
                        response = "{\"detail\":[\"Статус запроса " + servResp.StatusCode + "\"]}";
                    }
                }
            }

            return(json.ParseStrToObj <T>(response));
        }
 public void CompleteDeposit(string endpoint, UploadDataCompletedEventHandler completed, UploadProgressChangedEventHandler changed)
 {
     this.Headers["In-Progress"] = "false";
     this.UploadDataCompleted   += completed;
     this.UploadProgressChanged += changed;
     UploadDataAsync(new Uri(endpoint), "POST", new byte[0]);
 }
 public void DeleteResource(string endpoint, UploadDataCompletedEventHandler completed, UploadProgressChangedEventHandler changed)
 {
     this.UploadDataCompleted += completed;
     this.UploadProgressChanged += changed;
     UploadDataAsync(new Uri(endpoint), "DELETE", new byte[0]);
 }
Exemple #27
0
 /// <summary>
 /// 异步上传文件
 /// </summary>
 /// <param name="url">网络数据地址</param>
 /// <param name="fileFullName">本地文件地址</param>
 /// <param name="headers">请求标头</param>
 /// <param name="progressChanged">上传中</param>
 /// <param name="completed">上传完毕</param>
 public static void UploadFileAsync(string url, string fileFullName, NameValueCollection headers = null, UploadProgressChangedEventHandler progressChanged = null, UploadFileCompletedEventHandler completed = null)
 {
     using (WebClient client = new WebClient())
     {
         if (headers != null)
         {
             client.Headers.Add(headers);
         }
         if (progressChanged != null)
         {
             client.UploadProgressChanged += progressChanged;
         }
         if (completed != null)
         {
             client.UploadFileCompleted += completed;
         }
         client.UploadFileAsync(new Uri(url), "Http", fileFullName);
     }
 }
Exemple #28
0
        /// <summary>
        /// Uploads a file to an existing bucket.
        /// </summary>
        /// <param name="localFilePath">File Source Path</param>
        /// <param name="supabasePath">The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <string> Upload(string localFilePath, string supabasePath, FileOptions options = null, UploadProgressChangedEventHandler onProgress = null, bool inferContentType = true)
        {
            if (options == null)
            {
                options = new FileOptions();
            }

            if (inferContentType)
            {
                options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(localFilePath);
            }

            var result = await UploadOrUpdate(localFilePath, supabasePath, options, onProgress);

            return(result);
        }
Exemple #29
0
        private Task <string> UploadOrUpdate(byte[] data, string supabasePath, FileOptions options, UploadProgressChangedEventHandler onProgress = null)
        {
            var tsc = new TaskCompletionSource <string>();


            WebClient client = new WebClient();
            Uri       uri    = new Uri($"{Url}/object/{GetFinalPath(supabasePath)}");

            foreach (var header in Headers)
            {
                client.Headers.Add(header.Key, header.Value);
            }

            client.Headers.Add("cache-control", $"max-age={options.CacheControl}");
            client.Headers.Add("content-type", options.ContentType);

            if (options.Upsert)
            {
                client.Headers.Add("x-upsert", options.Upsert.ToString());
            }

            if (onProgress != null)
            {
                client.UploadProgressChanged += onProgress;
            }

            client.UploadDataCompleted += (sender, args) =>
            {
                if (args.Error != null)
                {
                    tsc.SetException(args.Error);
                }
                else
                {
                    tsc.SetResult(GetFinalPath(supabasePath));
                }
            };

            client.UploadDataAsync(uri, data);

            return(tsc.Task);
        }
Exemple #30
0
        /// <summary>
        /// Replaces an existing file at the specified path with a new one.
        /// </summary>
        /// <param name="localFilePath">File source path.</param>
        /// <param name="supabasePath">The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.</param>
        /// <param name="options">HTTP headers.</param>
        /// <returns></returns>
        public async Task <string> Update(byte[] data, string supabasePath, FileOptions options = null, UploadProgressChangedEventHandler onProgress = null)
        {
            if (options == null)
            {
                options = new FileOptions();
            }

            var result = await UploadOrUpdate(data, supabasePath, options);

            return(result);
        }
        private async void OnUploadToImgur(object sender, RoutedEventArgs e)
        {
            try
            {
                UploadProgressChangedEventHandler progress = (o, args) => TextEditor.Dispatcher.InvokeAsync(() =>
                {
                    if (_canceled)
                    {
                        ((WebClient)o).CancelAsync();
                    }
                    var progressPercentage = (int)(args.BytesSent / (double)args.TotalBytesToSend * 100);
                    ProgressBar.Value      = progressPercentage;
                    if (progressPercentage == 100)
                    {
                        ProgressBar.IsIndeterminate = true;
                    }
                });

                UploadValuesCompletedEventHandler completed = (o, args) =>
                {
                    if (_canceled)
                    {
                        ((WebClient)o).CancelAsync();
                    }
                };

                string name;
                byte[] image;

                if (_vm.UseClipboardImage)
                {
                    name  = "clipboard";
                    image = Images.ClipboardDibToBitmapSource().ToPngArray();
                }
                else
                {
                    var files = DroppedFiles();
                    if (files.Length > 1)
                    {
                        throw new Exception("Upload only 1 file at a time");
                    }
                    var path = files[0];
                    name  = Path.GetFileNameWithoutExtension(path);
                    image = File.ReadAllBytes(path);
                }

                _vm.Uploading      = true;
                ContextMenu.IsOpen = false;
                var link = await new ImageUploadImgur().UploadBytesAsync(image, progress, completed);
                ActivateClose();

                if (Uri.IsWellFormedUriString(link, UriKind.Absolute))
                {
                    InsertText(TextEditor, DragEventArgs, CreateImageTag(link, name));
                }
                else
                {
                    Notify.Alert(link);
                }
            }
            catch (Exception ex)
            {
                ActivateClose();
                Notify.Alert(ex.Message);
            }
        }
Exemple #32
0
        /// <summary>
        /// 上传图片到偷揉图库,暂定是这里。
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static async Task <string> UploadFileAsync(String FileName, UploadFileCompletedEventHandler uploadFileCompleted = null, UploadProgressChangedEventHandler uploadProgress = null)
        {
            String Html = "";
            CookieAwareWebClient ImgUpLoad = new CookieAwareWebClient();

            ImgUpLoad.Headers.Add("Referer", "x.mouto.org");
            ImgUpLoad.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");

            try
            {
                if (uploadFileCompleted != null)
                {
                    ImgUpLoad.UploadFileCompleted += uploadFileCompleted;
                }
                if (uploadProgress != null)
                {
                    ImgUpLoad.UploadProgressChanged += uploadProgress;
                }


                byte[] responseArray = await ImgUpLoad.UploadFileTaskAsync(new Uri("https://x.mouto.org/wb/x.php?up&_r=" + new Random().NextDouble()), FileName);



                String JsonText = Encoding.UTF8.GetString(responseArray);

                Root AllJson = JsonConvert.DeserializeObject <Root>(JsonText);
                Html = AllJson.pid;
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
            }
            return(Html);
        }