/// <summary> /// Uploads a file to the website using async /// </summary> /// <param name="URL">The URL to the website</param> /// <param name="path">The path to the file to upload</param> /// <param name="method">The method to run once the upload is done</param> /// <param name="useNewClient">Use a new client</param> /// <param name="client">A custom client(leave null to create a new one)</param> /// <returns>If the file was uploaded successfully</returns> public static bool UploadFileAsync(string URL, string path, UploadFileCompletedEventHandler method = null, bool useNewClient = true, WeebClient client = null) { try { if (useNewClient || client == null) { WeebClient wc = new WeebClient(); wc.UploadFileCompleted += new UploadFileCompletedEventHandler(OnUploadFile); if (method != null) { wc.UploadFileCompleted += method; } wc.UploadFileAsync(new Uri(URL), path); return(true); } client.UploadFileAsync(new Uri(URL), path); return(true); } catch (Exception ex) { PointBlankLogging.LogError("Failed to upload file via async to " + URL, ex, false, false); return(false); } }
/// <summary>Uploads a file to the specified resource, asynchronously.</summary> /// <param name="webClient">The WebClient.</param> /// <param name="address">The URI to which the file should be uploaded.</param> /// <param name="method">The HTTP method that should be used to upload the file.</param> /// <param name="fileName">A path to the file to upload.</param> /// <returns>A Task containing the data in the response from the upload.</returns> public static Task <byte[]> UploadFileTask( this WebClient webClient, Uri address, string method, string fileName) { // Create the task to be returned var tcs = new TaskCompletionSource <byte[]>(address); // Setup the callback event handler UploadFileCompletedEventHandler handler = null; handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadFileCompleted -= handler); webClient.UploadFileCompleted += handler; // Start the async work try { webClient.UploadFileAsync(address, method, fileName, tcs); } catch (Exception exc) { // If something goes wrong kicking off the async work, // unregister the callback and cancel the created task webClient.UploadFileCompleted -= handler; tcs.TrySetException(exc); } // Return the task that represents the async operation return(tcs.Task); }
/// <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) }; }
/// <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); }
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; }
/// <summary> /// This event is raised each time file upload operation completes. /// </summary> private void Gett_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e) { UploadFileCompletedEventHandler copyUploadFileCompleted = UploadFileCompleted; if (copyUploadFileCompleted != null) { copyUploadFileCompleted(this, e); } }
/// <summary> /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed. /// <example> /// uploadfilecompletedeventhandler.BeginInvoke(sender, e, callback); /// </example> /// </summary> public static IAsyncResult BeginInvoke(this UploadFileCompletedEventHandler uploadfilecompletedeventhandler, Object sender, UploadFileCompletedEventArgs e, AsyncCallback callback) { if (uploadfilecompletedeventhandler == null) { throw new ArgumentNullException("uploadfilecompletedeventhandler"); } return(uploadfilecompletedeventhandler.BeginInvoke(sender, e, callback, null)); }
/// <summary> /// 异步上传文件到到指定的Url页面。其中filePath为本地文件全路径,uploadFinish表示发送成功时执行的委托 /// </summary> public static void PostFile(string filePath, string url, UploadFileCompletedEventHandler uploadFinish) { WebClient wc = new WebClient(); wc.QueryString.Add("date", DateTime.Now.Millisecond + ""); if (uploadFinish != null) { wc.UploadFileCompleted += uploadFinish; } wc.UploadFileAsync(new Uri(url), filePath); }
/// <summary>Uploads a file to the specified resource, asynchronously.</summary> /// <param name="webClient">The WebClient.</param> /// <param name="address">The URI to which the file should be uploaded.</param> /// <param name="method">The HTTP method that should be used to upload the file.</param> /// <param name="fileName">A path to the file to upload.</param> /// <returns>A Task containing the data in the response from the upload.</returns> public static Task <byte[]> UploadFileTaskAsync(this WebClient webClient, Uri address, string method, string fileName) { // Create the task to be returned var tcs = new TaskCompletionSource <byte[]>(address); // Setup the callback event handler UploadFileCompletedEventHandler handler = null; handler = (sender, e) => TaskServices.HandleEapCompletion(tcs, true, e, () => e.Result, () => webClient.UploadFileCompleted -= handler); webClient.UploadFileCompleted += handler; // Start the async operation. try { webClient.UploadFileAsync(address, method, fileName, tcs); } catch { webClient.UploadFileCompleted -= handler; throw; } // Return the task that represents the async operation return(tcs.Task); }
/// <summary>Uploads a file to the specified resource, asynchronously.</summary> /// <param name="webClient">The WebClient.</param> /// <param name="address">The URI to which the file should be uploaded.</param> /// <param name="method">The HTTP method that should be used to upload the file.</param> /// <param name="fileName">A path to the file to upload.</param> /// <returns>A Task containing the data in the response from the upload.</returns> public static Task <byte[]> UploadFileTask(this WebClient webClient, Uri address, string method, string fileName) { TaskCompletionSource <byte[]> tcs = new TaskCompletionSource <byte[]>(address); UploadFileCompletedEventHandler handler = null; handler = delegate(object sender, UploadFileCompletedEventArgs e) { EAPCommon.HandleCompletion <byte[]>(tcs, e, () => e.Result, delegate { webClient.UploadFileCompleted -= handler; }); }; webClient.UploadFileCompleted += handler; try { webClient.UploadFileAsync(address, method, fileName, tcs); } catch (Exception exception) { webClient.UploadFileCompleted -= handler; tcs.TrySetException(exception); } return(tcs.Task); }
/// <summary> /// <paramref name="address"/>에 <paramref name="filename"/>의 파일을 전송합니다. (HTTP나 FTP나 같습니다) /// </summary> /// <param name="webClient"><see cref="WebClient"/> 인스턴스</param> /// <param name="address">전송할 주소</param> /// <param name="method">전송 방법 (HTTP는 POST, FTP는 STOR)</param> /// <param name="filename">전송할 파일의 전체경로</param> /// <returns></returns> public static Task <byte[]> UploadFileTask(this WebClient webClient, Uri address, string method, string filename) { webClient.ShouldNotBeNull("webClient"); address.ShouldNotBeNull("address"); filename.ShouldNotBeWhiteSpace("filename"); Guard.Assert <FileNotFoundException>(File.Exists(filename), "File not found. filename=[{0}]", filename); if (IsDebugEnabled) { log.Debug("지정된 주소에 파일을 비동기 방식으로 Upload합니다... address=[{0}], method=[{1}], filename=[{2}]", address.AbsoluteUri, method, filename); } var tcs = new TaskCompletionSource <byte[]>(address); UploadFileCompletedEventHandler handler = null; handler = (s, e) => EventAsyncPattern.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadFileCompleted -= handler); webClient.UploadFileCompleted += handler; try { webClient.UploadFileAsync(address, method, filename, tcs); } catch (Exception ex) { if (log.IsWarnEnabled) { log.Warn("WebClient를 이용하여 파일을 비동기 방식 Upload에 실패했습니다. address=[{0}]" + address.AbsoluteUri); log.Warn(ex); } webClient.UploadFileCompleted -= handler; tcs.TrySetException(ex); } return(tcs.Task); }
public static Task <byte[]> UploadFileTaskAsync(this WebClient webClient, Uri address, string method, string fileName) { TaskCompletionSource <byte[]> tcs = new TaskCompletionSource <byte[]>(address); UploadFileCompletedEventHandler handler = null; handler = delegate(object sender, UploadFileCompletedEventArgs e) { AsyncCompatLibExtensions.HandleEapCompletion <byte[]>(tcs, true, e, () => e.Result, delegate { webClient.UploadFileCompleted -= handler; }); }; webClient.UploadFileCompleted += handler; try { webClient.UploadFileAsync(address, method, fileName, tcs); } catch { webClient.UploadFileCompleted -= handler; throw; } return(tcs.Task); }
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); } }); }
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 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); } }
/// <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); } }