private void skinButton1_Click(object sender, EventArgs e) { openFileDialog1.FileName = ""; //对话框初始化 openFileDialog1.ShowDialog();//显示对话框 String total_filename=openFileDialog1.FileName; String short_filename=openFileDialog1.SafeFileName; //MessageBox.Show(total_filename); if (short_filename.ToString() != "") { String keyword = Microsoft.VisualBasic.Interaction.InputBox("请输入口令:", "安全验证"); //对输入的口令进行加密运算 string md5_password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(keyword.ToString(), "MD5"); //MessageBox.Show(password); if (md5_password.ToString() == "16F09AE0A377EDE6206277FAD599F9A0") { String url_link = "ftp://*****:*****@133.130.89.177/" + short_filename; WebClient wc = new WebClient(); wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged); wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted); wc.UploadFileAsync(new Uri(url_link), total_filename); skinButton1.Enabled = false; skinButton1.ForeColor = System.Drawing.Color.Black; //计算用时,计算上传速度 sw.Reset(); sw.Start(); } else MessageBox.Show("口令验证失败!"); } }
protected static WebClient UploadFileInternal(String token, String localFilePath, bool isAync) { try { String uploadReqJson = "{\"token\":\"" + token + "\"}"; String uploadUrl = RequestUploadUrl(uploadReqJson); Int64 fileSize = new System.IO.FileInfo(localFilePath).Length; var client = new System.Net.WebClient(); client.Headers.Add("Content-Range", "bytes 0-" + (fileSize - 1).ToString() + "/" + fileSize.ToString()); //client.Headers.Add("Content-Type", "application/octet-stream"); client.Headers.Add("Content-MD5", GetFileMD5Hex(localFilePath)); if (isAync) { client.UploadFileAsync(new Uri(uploadUrl), localFilePath); } else { client.UploadFile(new Uri(uploadUrl), localFilePath); } return(client); } catch (WebException e) { throw new CloudException(99, e.ToString()); } }
/// <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); }
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; }
public void UploadFile(string url, string filePath) { WebClient webClient = new WebClient(); Uri siteUri = new Uri(url); webClient.UploadProgressChanged += WebClientUploadProgressChanged; webClient.UploadFileCompleted += WebClientUploadCompleted; webClient.UploadFileAsync(siteUri, "POST", filePath); }
public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data, NameValueCollection values) { System.Net.WebClient webclient = new System.Net.WebClient(); // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file" //webclient.Download * (...); // Any method starting with "Download" webclient.DownloadData(address); // Noncompliant webclient.DownloadDataAsync(uriAddress, new object()); // Noncompliant webclient.DownloadDataTaskAsync(uriAddress); // Noncompliant webclient.DownloadFile(address, "filename"); // Noncompliant webclient.DownloadFileAsync(uriAddress, "filename"); // Noncompliant webclient.DownloadFileTaskAsync(address, "filename"); // Noncompliant webclient.DownloadString(uriAddress); // Noncompliant webclient.DownloadStringAsync(uriAddress, new object()); // Noncompliant webclient.DownloadStringTaskAsync(address); // Noncompliant // Should not raise for events webclient.DownloadDataCompleted += Webclient_DownloadDataCompleted; webclient.DownloadFileCompleted += Webclient_DownloadFileCompleted; webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged; webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted; //webclient.Open * (...); // Any method starting with "Open" webclient.OpenRead(address); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Make sure that this http request is sent safely.}} webclient.OpenReadAsync(uriAddress, new object()); // Noncompliant webclient.OpenReadTaskAsync(address); // Noncompliant webclient.OpenWrite(address); // Noncompliant webclient.OpenWriteAsync(uriAddress, "STOR", new object()); // Noncompliant webclient.OpenWriteTaskAsync(address, "POST"); // Noncompliant webclient.OpenReadCompleted += Webclient_OpenReadCompleted; webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted; //webclient.Upload * (...); // Any method starting with "Upload" webclient.UploadData(address, data); // Noncompliant webclient.UploadDataAsync(uriAddress, "STOR", data); // Noncompliant webclient.UploadDataTaskAsync(address, "POST", data); // Noncompliant webclient.UploadFile(address, "filename"); // Noncompliant webclient.UploadFileAsync(uriAddress, "filename"); // Noncompliant webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant webclient.UploadString(uriAddress, "data"); // Noncompliant webclient.UploadStringAsync(uriAddress, "data"); // Noncompliant webclient.UploadStringTaskAsync(uriAddress, "data"); // Noncompliant webclient.UploadValues(address, values); // Noncompliant webclient.UploadValuesAsync(uriAddress, values); // Noncompliant webclient.UploadValuesTaskAsync(address, "POST", values); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Should not raise for events webclient.UploadDataCompleted += Webclient_UploadDataCompleted; webclient.UploadFileCompleted += Webclient_UploadFileCompleted; webclient.UploadProgressChanged -= Webclient_UploadProgressChanged; webclient.UploadStringCompleted -= Webclient_UploadStringCompleted; webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted; }
void Upload() { WebClient client = new System.Net.WebClient(); Uri uri = new Uri(FTPHost + "/" + new FileInfo(FilePath).Name); client.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword); client.UploadFileAsync(uri, "STOR", FilePath); }
public void UploadFile(string FilePath) { Debug.Log("Path: " + FilePath); WebClient client = new System.Net.WebClient(); Uri uri = new Uri(FTPHost + "/" + new FileInfo(FilePath).Name); client.UploadProgressChanged += new UploadProgressChangedEventHandler(OnFileUploadProgressChanged); client.UploadFileCompleted += new UploadFileCompletedEventHandler(OnFileUploadCompleted); client.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword); client.UploadFileAsync(uri, "STOR", FilePath); }
private void CloudUploader_Load(object sender, EventArgs e) { progress.Value = 0; bool isImage = contentType.IndexOf("image") == 0; WebClient uploader = new WebClient(); string param = "ContentType=" + Uri.EscapeUriString(contentType); param += "&isAttachment=" + Uri.EscapeUriString((!isImage).ToString()); param += "&LiveToken=" + CloudCommunities.GetTokenFromId(true); uploader.UploadProgressChanged += new UploadProgressChangedEventHandler(uploader_UploadProgressChanged); uploader.UploadFileCompleted += new UploadFileCompletedEventHandler(uploader_UploadFileCompleted); uploader.UploadFileAsync(new Uri(Properties.Settings.Default.WWTCommunityServer + "FileUploader.aspx?" + param), filename); }
public void UploadFile() { FilePath = Application.dataPath + "/StreamingAssets/test.txt"; WebClient client = new System.Net.WebClient(); Uri uri = new Uri(FTPHost + new FileInfo(FilePath).Name); client.UploadProgressChanged += new UploadProgressChangedEventHandler(OnFileUploadProgressChanged); client.UploadFileCompleted += new UploadFileCompletedEventHandler(OnFileUploadCompleted); client.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword); client.UploadFileAsync(uri, "STOR", FilePath); }
/// <summary> /// Uploads a file to the FTP server /// </summary> /// <param name="infilepath">Local filepath of file</param> /// <param name="outfilepath">Target filepath on FTP server</param> /// <returns></returns> public static bool UploadFile(string infilepath, string outfilepath) { using (var request = new WebClient()) { request.Credentials = DefaultCredentials; try { request.UploadFileAsync(new Uri($"ftp://{ServerAddress}/{outfilepath}"), "STOR", infilepath); return true; } catch (WebException ex) { Logger.Write(ex.Message); return false; } } }
private void btn_Upload_Click(object sender, EventArgs e) { btn_Selectfile.Enabled = false; btn_Upload.Enabled = false; using (WebClient client = new WebClient()) { string fileName = openFileDialog1.FileName; Uri url_upload = new Uri("change recive remote url"); NameValueCollection nvc = new NameValueCollection(); // data insert // nvc.Add("userid", "user01"); // nvc.Add("workid", "work01"); client.QueryString = nvc; client.UploadFileCompleted += (s, e1) => { string msg; btn_Selectfile.Enabled = true; btn_Upload.Enabled = true; msg = Encoding.UTF8.GetString(e1.Result); MessageBox.Show(msg); }; client.UploadProgressChanged += (s, e1) => { double BytesSent = e1.BytesSent; double TotalBytesToSend = e1.TotalBytesToSend; int percent = (int)((BytesSent / TotalBytesToSend) * 100.0); prog_Upload.Value = percent; lbl_Percent.Text = percent + "%"; }; client.UploadFileAsync(url_upload, fileName); client.Dispose(); } }
/// <summary> /// Uploads a file to the specified resource. /// </summary> /// <param name="client">The object that uploads to the resource.</param> /// <param name="address">The URI of the resource to receive the file.</param> /// <param name="method">The HTTP method used to send data to the resource. If <see langword="null"/>, the default is POST for HTTP and STOR for FTP.</param> /// <param name="fileName">The file to upload to the resource.</param> /// <returns>An observable that caches the response from the server and replays it to observers.</returns> public static IObservable <byte[]> UploadFileObservable( this WebClient client, Uri address, string method, string fileName) { Contract.Requires(client != null); Contract.Requires(address != null); Contract.Requires(fileName != null); Contract.Ensures(Contract.Result <IObservable <byte[]> >() != null); return(Observable2.FromEventBasedAsyncPattern <UploadFileCompletedEventHandler, UploadFileCompletedEventArgs>( handler => handler.Invoke, handler => client.UploadFileCompleted += handler, handler => client.UploadFileCompleted -= handler, token => client.UploadFileAsync(address, method, fileName, token), client.CancelAsync) .Select(e => e.EventArgs.Result)); }
public static void doUploadPhoto(Activity activity, String filePath) { string imgpath = ""; try { System.Net.WebClient Client = new System.Net.WebClient(); Client.Headers.Add("Content-Type", "binary/octet-stream"); Client.UploadFileAsync(new Uri(Global.imgUploadPath), "POST", filePath); Client.UploadFileCompleted += delegate(object sender, UploadFileCompletedEventArgs e) { imgpath = System.Text.Encoding.UTF8.GetString(e.Result, 0, e.Result.Length); activity.RunOnUiThread(() => { ((SignupActivity)activity).uploadPhotoWithResult(imgpath); }); }; } catch (Exception e) { } }
private void Start() { if (archivo != "") { try { System.Net.WebClient Client = new System.Net.WebClient(); // Client.Headers.Add("Content-Type", "binary/octet-stream"); Client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCompleted); Client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressChanged); Client.UploadFileAsync(server, "POST", archivo); } catch (Exception ex) { MessageBox.Show("ERRROR: " + ex.Message); } } }
/// <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); }
private void UploadFile(string path) { if (!File.Exists(path)) { Log.WriteLog("File not found"); Log.WriteLog(path); ShowNotify("File not found", "Error", System.Windows.Forms.ToolTipIcon.Error); return; } ChangeTray(true); WebClient client = new System.Net.WebClient() { Proxy = null }; client.Headers.Add("Content-Type", "binary/octet-stream"); client.Headers.Add("Accept-Token", Setting.Token); client.UploadFileCompleted += client_UploadFileCompleted; client.UploadFileAsync(new UriBuilder(String.Format("http://{0}/upload.php", Setting.Server)).Uri, "POST", path); }
private void uploadToSite() { if (Clipboard.ContainsImage() == true && !uploading) { label1.Text = "Uploading..."; uploading = true; string website; path = Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToString("yyyyMMdd HHmmss") + ".jpg"; website = "http://wizzed.net/imageupload/uploadz.php"; System.Net.WebClient client = new System.Net.WebClient(); client.Headers.Add("Content-Type", "binary/octet-stream"); Image test = Clipboard.GetImage(); EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L); ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg"); test.Save(path, codecInfo, parameters); Object o = new Object(); Uri webUri = new Uri(website); client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCallback); client.UploadFileAsync(webUri, "POST", path, o); //timer1.Start(); } }
private void doUpload(string filePath) { string folder = filePath.Substring(0, filePath.LastIndexOf("\\")); string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1); fileName = folder + "\\" + fileName.Substring(0, fileName.LastIndexOf(".")) + ".zip"; string teacher = ""; string course = ""; string year = ""; try { dynamic config = JsonConvert.DeserializeObject(File.ReadAllText(folder + @"\__.w2hc")); teacher = config.teacher; course = config.course; year = config.year; } catch (Exception ex) { } string endPoint = string.Format( "http://eshia.ir/feqh/archive/convert2zip/{0}/{1}/{2}", Uri.EscapeDataString(teacher), Uri.EscapeDataString(course), Uri.EscapeDataString(year) ); WebClient wc = new WebClient(); wc.UploadProgressChanged += (o, ea) => { if (ea.ProgressPercentage >= 0 && ea.ProgressPercentage <= 100) { documentsProgress[filePath] = ea.ProgressPercentage; toolStripProgressBar1.Value = computeProgress(); } }; wc.UploadFileCompleted += (o, ea) => { if (ea.Error == null) { string response = Encoding.UTF8.GetString(ea.Result); try { dynamic result = JsonConvert.DeserializeObject(response); if (result.success == "yes") { using ( BinaryWriter bw = new BinaryWriter( new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite) ) ) { string content = result.content; byte[] data = Convert.FromBase64String(content); bw.Write(data); } FastZip fastZip = new FastZip(); string fileFilter = null; try { // Will always overwrite if target filenames already exist fastZip.ExtractZip(fileName, folder, fileFilter); File.Delete(fileName); } catch (Exception ex) { } //textBox2.Text = "Upload completed."; documentsCompleted.Add(filePath); } else { //textBox2.Text = "Upload failed."; documentsFailed.Add(filePath); } } catch (Exception ex) { //textBox2.Text = "Upload failed."; documentsFailed.Add(filePath); } } else { //textBox2.Text = "Upload failed."; documentsFailed.Add(filePath); } }; wc.UploadFileAsync(new Uri(endPoint), filePath); }
private void UploadToHttp(string filePath) { string fileName = Path.GetFileNameWithoutExtension(filePath); int version = GetPracticeVersion(fileName); var client = new WebClient(); _uploadWindow.FileName.Text = fileName; _uploadWindow.Show(); client.UploadProgressChanged += progressHandler; client.UploadFileCompleted += UploadCompleted; client.UploadFileAsync(new Uri(ConfigurationManager.AppSettings.Get("httpAddress") + fileName + "/" + version), "POST", filePath); }
protected static WebClient UploadFileInternal(String token, String localFilePath, bool isAync) { try { String uploadReqJson = "{\"token\":\"" + token + "\"}"; String uploadUrl = RequestUploadUrl(uploadReqJson); Int64 fileSize = new System.IO.FileInfo(localFilePath).Length; var client = new System.Net.WebClient(); client.Headers.Add("Content-Range", "bytes 0-" + (fileSize - 1).ToString() + "/" + fileSize.ToString()); //client.Headers.Add("Content-Type", "application/octet-stream"); client.Headers.Add("Content-MD5", GetFileMD5Hex(localFilePath)); if (isAync) client.UploadFileAsync(new Uri(uploadUrl), localFilePath); else client.UploadFile(new Uri(uploadUrl), localFilePath); return client; } catch (WebException e) { throw new CloudException(99, e.ToString()); } }
internal void SendFilePacket(Packet packet) { Uri uri = new Uri(this.GetUrl("data/upload")); try { using (WebClient wc = new WebClient()) { wc.UploadFileCompleted += (object sender, UploadFileCompletedEventArgs e) => { if (e.Error != null) { return; } Packet p = (Packet)e.UserState; if (p != null) { // TODO: with p.Path } }; wc.UploadFileAsync(uri, Post, packet.Path, packet); } } catch (WebException) { } }
bool __upload(string what, string path) { fdata = path; WebClient client = new WebClient(); client.Credentials = new NetworkCredential(Login, Password); Uri uri = new Uri(Host + "/" + what); client.Headers.Add("ContentType","application/json"); try { if (fProgress == null) { byte[] rc = client.UploadFile(uri, path); if (rc != null) { string s = convert.GetString(rc); __message(null,s); } __endTask(this, Path.GetFileName(path) + "."); } else { client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback); client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadCompletedCallback); client.UploadFileAsync(uri, path); } return true; } catch (WebException e) { web_error(e,"upload"); } return false; }
public void UpLoadImage(string fileName) { try { WebClient wc = new WebClient(); wc.UploadFileCompleted += UploadImageRequestCompleted; wc.UploadFileAsync(new Uri(UploadImageUrl), fileName); } catch (Exception ex) { MessageBoxResult result = MessageBox.Show(ex.Message, "Network error"); Debug.WriteLine(ex.Message); MainWindow win = (MainWindow)Application.Current.MainWindow; win.ProgressBar.Visibility = Visibility.Collapsed; this.Visibility = Visibility.Visible; } }
private void OnlinePackagerBtn_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(InstallerPath)) return; ValidatePackagingMethods(InstallerPath); // Validate cloud packaging: unattended install? bool silentInstallAvailable = Utils.SilentInstallAvailable(Utils.MyPath("SilentInstall.exe"), InstallerPath); if (!silentInstallAvailable) { if (MessageBox.Show("This file does not support unattended installation. " + "You will need to finalize this request online. Would you like to proceed?", "Confirmation", MessageBoxButton.YesNo) != MessageBoxResult.Yes) return; } // Check if online packaging is possible (i.e. account limits) if (!string.IsNullOrEmpty(CannotOnlinePackagerReason)) { MessageBox.Show(CannotOnlinePackagerReason); return; } // Submit file string args = ""; if (!string.IsNullOrEmpty(InstallerArgs)) args = "&args=" + InstallerArgs; var url = Server.BuildUrl("PkgSubmitFile", true, args); var webClient = new WebClient(); webClient.UploadProgressChanged += UploadProgressChanged; webClient.UploadFileCompleted += SubmitPkgFileUploadCompleted; webClient.UploadFileAsync(new Uri(url), InstallerPath); ProgressText("Uploading"); SetUiMode(UiMode.Working); }
private void RemoteInstallBtn_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(InstallerPath)) return; ValidatePackagingMethods(InstallerPath); // ToDo: validate installer file // Check if online packaging is possible (i.e. account limits) if (!string.IsNullOrEmpty(CannotOnlinePackagerReason)) { MessageBox.Show(CannotOnlinePackagerReason); return; } // Submit file string args = ""; if (!string.IsNullOrEmpty(InstallerArgs)) args = "&args=" + InstallerArgs; var url = Server.BuildUrl("RdpCapture", false, "&client=Play.WinTSC"); url += "&" + Server.AuthUrl(); var webClient = new WebClient(); webClient.UploadProgressChanged += UploadProgressChanged; webClient.UploadFileCompleted += SubmitRdpCaptureFileUploadCompleted; webClient.UploadFileAsync(new Uri(url), InstallerPath); ProgressText("Uploading"); SetUiMode(UiMode.Working); }
public void Perform(string localFilePath) { // TODO - replace with production value var host = HttpConfig.Protocol + HttpConfig.Host; if (Reachability.InternetConnectionStatus() == NetworkStatus.NotReachable) { ReportInAppFailure(ErrorDescriptionProvider.NetworkUnavailableErrorCode); return; } if (!Reachability.IsHostReachable(host)) { ReportInAppFailure(ErrorDescriptionProvider.HostUnreachableErrorCode); return; } if (!File.Exists(localFilePath)) { ReportInAppFailure(ErrorDescriptionProvider.FileNotFoundErrorCode); return; } using (client = new WebClient()) { client.UploadProgressChanged += OnProgressUpdated; client.UploadFileCompleted += OnUploadCompleted; Debug.WriteLine("Begining upload"); // TODO - change to production URI client.UploadFileAsync(new Uri("http://www.roweo.pl/api/user/image_upload", UriKind.Absolute), localFilePath); } }
public void UpLoadImage(string fileName) { WebClient wc = new WebClient(); wc.UploadFileCompleted += UploadImageRequestCompleted; wc.UploadFileAsync(new Uri(UploadImageUrl), fileName); }
//--------------------// #region Buttons private void buttonReport_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; commentBox.Enabled = detailsBox.Enabled = buttonReport.Enabled = buttonCancel.Enabled = false; // Create WebClient for upload and register as component for automatic disposal var webClient = new WebClient(); if (components == null) components = new Container(); components.Add(webClient); webClient.UploadFileCompleted += OnUploadFileCompleted; webClient.UploadFileAsync(_uploadUri, GenerateReportFile()); }
/// <summary> /// Starts the upgrading process. /// </summary> /// <param name="server">The endpoint for the migration script.</param> public void Start(Uri server) { _tdstr = "Connecting to " + server.DnsSafeHost + "..."; var mthd = new Thread(() => TaskDialog.Show(new TaskDialogOptions { Title = "Upgrading...", MainInstruction = "Upgrading TVShows.db3", Content = "Connecting to " + server.DnsSafeHost + "...", CustomButtons = new[] { "Cancel" }, ShowProgressBar = true, EnableCallbackTimer = true, AllowDialogCancellation = true, Callback = (dialog, args, data) => { try { dialog.SetProgressBarPosition(_tdpos); dialog.SetContent(_tdstr); if (args.ButtonId != 0) { Utils.Win7Taskbar(state: TaskbarProgressBarState.NoProgress); if (!_cancel) { try { _wc.CancelAsync(); } catch { } } return false; } if (_cancel) { dialog.ClickButton(500); return false; } } catch { return false; } return true; } })); mthd.SetApartmentState(ApartmentState.STA); mthd.Start(); _wc = new WebClient(); _wc.UploadFileAsync(server, Path.Combine(Signature.InstallPath, "TVShows.db3.gz")); _wc.UploadProgressChanged += (s, a) => { if (a.ProgressPercentage > 0 && a.ProgressPercentage < 50) { _tdpos = (int)Math.Round((double)a.BytesSent / (double)a.TotalBytesToSend * 100); _tdstr = "Uploading database file for conversion... ({0:0.00}%)".FormatWith((double)a.BytesSent / (double)a.TotalBytesToSend * 100); } else if (a.ProgressPercentage == 50) { _tdpos = 100; _tdstr = "Waiting for conversion to complete..."; } else if (a.ProgressPercentage < 0) { _tdstr = "Downloading converted database... ({0})".FormatWith(Utils.GetFileSize(a.BytesReceived)); } }; _wc.UploadFileCompleted += WebClientOnUploadFileCompleted; }
void SubmitFile() { // Upload request PkgUploaded = true; // Avoid the "Download" button from now on var url = Server.BuildUrl("PkgSubmitFile", true, null); var webClient = new WebClient(); webClient.UploadProgressChanged += UploadProgressChanged; webClient.UploadFileCompleted += SubmitPkgFileUploadCompleted; webClient.UploadFileAsync(new Uri(url), PkgLocation); ProgressText("Uploading"); SetUiMode(UiMode.DownloadingUploading); }
public void UploadFileAsync(string filePath, StatusProgressChanged uploadProgressChanged, StatusChanged uploadCompleted) { if (CurrentSecret == null) return; var destinationPath = String.Format ("/api/{0}/{1}", CurrentSecret, UrlHelper.GetFileName (filePath)); var client = new WebClient (); client.Headers ["content-type"] = "application/octet-stream"; client.Encoding = Encoding.UTF8; client.UploadProgressChanged += (sender, e) => { uploadProgressChanged (e); }; client.UploadFileCompleted += (sender, e) => { uploadCompleted (); if (e.Cancelled) { Console.Out.WriteLine ("Upload file cancelled."); return; } if (e.Error != null) { Console.Out.WriteLine ("Error uploading file: {0}", e.Error.Message); return; } var response = System.Text.Encoding.UTF8.GetString (e.Result); if (!String.IsNullOrEmpty (response)) { } }; Send (destinationPath); client.UploadFileAsync (new Uri (SERVER + destinationPath), "POST", filePath); }
private void button1_Click(object sender, EventArgs e) { #region 上传图片并生成新html Regex r = new Regex("<IMG[\\s\\S]*?>"); MatchCollection mc = r.Matches(htmlEditor1.BodyInnerHTML); ///string[] mc = CommonClass.HtmlUtility.GetElementsByTagName(htmlEditor1.BodyInnerHTML, "IMG"); String html = htmlEditor1.BodyInnerHTML; Uri endpoint = new Uri(Securit.DeDES(IniReadAndWrite.IniReadValue("fileManage", "filePath"))); for (int i = 0; i < mc.Count; i++) { if (mc[i].Value.Contains("src=\"http://")) { continue; } using (WebClient myWebClient = new WebClient()) { myWebClient.UploadFileCompleted += new UploadFileCompletedEventHandler(uploadCompleted); String imgHtml = mc[i].Value; string inPath = HtmlUtility.GetTitleContent(imgHtml, "img", "src"); //imgHtml.Substring(startIndex, imgHtml.LastIndexOf("\"") - startIndex); try { String newName = user.Id + "_" + DateTime.Now.Ticks + inPath.Substring(inPath.LastIndexOf(".")); String tempPath = Application.StartupPath.ToString() + "\\temp\\" + newName; File.Copy(inPath, tempPath, true); myWebClient.UploadFileAsync(endpoint, tempPath); String newString2 = imgHtml.Remove(imgHtml.IndexOf("src"), inPath.Length + 6);//.Remove(imgHtml.LastIndexOf('>'))+" src=\"" + Securit.DeDES(IniReadAndWrite.IniReadValue("fileManage", "savePath")) + newName + "\">"; string newString1 = newString2.Remove(newString2.LastIndexOf('>')); string newString = newString1 + " src=\"" + Securit.DeDES(IniReadAndWrite.IniReadValue("fileManage", "savePath"))+@"LogPic\" + newName + "\">"; //html html = html.Replace(mc[i].Value, newString); } catch (Exception exp) { MessageBox.Show(exp.ToString()); return; } } } #endregion StaffLog staffLog = null; if (htmlEditor1.Tag == null) { staffLog = new StaffLog(); } else if (htmlEditor1.Tag != null) { staffLog = (StaffLog)htmlEditor1.Tag; } staffLog.Content = html; staffLog.State = (int)IEntity.stateEnum.Normal; staffLog.WriteTime = DateTime.Now.Ticks; staffLog.TimeStamp = DateTime.Now.Ticks; staffLog.Staff = user; staffLog.SharedStaffs = sharedUser; try { if (staffLog.Id == 0) { object be = baseService.saveEntity(staffLog); staffLog.Id = int.Parse(be.ToString()); } else if (staffLog.Id != 0) { baseService.SaveOrUpdateEntity(staffLog); } #region 向服务中发送数据 try { KjqbService.Service1Client ser = new KjqbService.Service1Client(); if (sharedUser != null && sharedUser.Count > 0) { foreach (WkTUser u in sharedUser) { KjqbService.LogInService ll = new KjqbService.LogInService(); ll.LogId = staffLog.Id; ll.WriteUserId = this.user.Id; ll.ShareUserId = u.Id; ll.TimeStamp = DateTime.Now.Ticks; ser.SaveInLogListInService(ll); } } } catch { } #endregion } catch { MessageBox.Show("保存失败!"); return; } MessageBox.Show("保存成功!"); this.DialogResult = DialogResult.OK; this.Close(); }
/// <summary> /// Uploads a document into Scribd asynchronously. /// </summary> /// <param name="request"></param> internal void PostFileUploadRequest(Request request) { // Set up our Event arguments for subscribers. ServicePostEventArgs _args = new ServicePostEventArgs(request.RESTCall, request.MethodName); // Give subscribers a chance to stop this before it gets ugly. OnBeforePost(_args); if (!_args.Cancel) { // Ensure we have the min. necessary params. if (string.IsNullOrEmpty(Service.APIKey)) { OnErrorOccurred(10000, Properties.Resources.ERR_NO_APIKEY); return; } else if (Service.SecretKeyBytes == null) { OnErrorOccurred(10001, Properties.Resources.ERR_NO_SECRETKEY); return; } if (!request.SpecifiedUser) { // Hook up our current user. request.User = InternalUser; } try { // Set up our client to call API using (WebClient _client = new WebClient()) { // Set up the proxy, if available. if (Service.WebProxy != null) { _client.Proxy = Service.WebProxy; } // Special case - need to upload multi-part POST if (request.MethodName == "docs.upload" || request.MethodName == "docs.uploadThumb") { // Get our filename from the request, then dump it! // (Scribd doesn't like passing the literal "file" param.) string _fileName = request.Parameters["file"]; request.Parameters.Remove("file"); // Make that call. _client.UploadProgressChanged += new UploadProgressChangedEventHandler(_client_UploadProgressChanged); _client.UploadFileCompleted += new UploadFileCompletedEventHandler(_client_UploadFileCompleted); _client.UploadFileAsync(new Uri(request.RESTCall), "POST", _fileName); } else { return; } } } catch (Exception ex) { // Something unexpected? OnErrorOccurred(666, ex.Message, ex); } finally { OnAfterPost(_args); } } return; }
/// <summary> /// Upload file content asynchron. /// Progress is signaled via UploadProgressChanged and UploadFileCompleted event. /// </summary> /// <param name="fileName">File to upload content</param> public void UploadFileEvents(string fileName) { lock (_syncRootAsync) { // Abort other operation. if (_gettAsync != null) { _gettAsync.DownloadDataCompleted -= Gett_DownloadDataCompleted; _gettAsync.DownloadFileCompleted -= Gett_DownloadFileCompleted; _gettAsync.DownloadProgressChanged -= Gett_DownloadProgressChanged; _gettAsync.UploadDataCompleted -= Gett_UploadDataCompleted; _gettAsync.UploadFileCompleted -= Gett_UploadFileCompleted; _gettAsync.UploadProgressChanged -= Gett_UploadProgressChanged; if (_gettAsync.IsBusy) _gettAsync.CancelAsync(); } // GET request _gettAsync = new WebClient(); _gettAsync.UploadFileCompleted += Gett_UploadFileCompleted; _gettAsync.UploadProgressChanged += Gett_UploadProgressChanged; _gettAsync.UploadFileAsync(new Uri(_gettFileInfo.Upload.PostUrl), fileName); } }
/// <summary> /// Upload File /// </summary> /// <param name="packet"></param> internal void SendFilePacket(Packet packet) { if (string.IsNullOrEmpty(packet.Path) || !File.Exists(packet.Path)) { Notify msg = new Notify(); msg.Message = "No File Found"; this.NotifyEvent(this, NotifyEvents.EventMessage, msg); return; } string uploadUrl = string.Empty; if (packet.FileType.Equals("labr", StringComparison.OrdinalIgnoreCase)) { string path = Path.GetDirectoryName(packet.Path); var folder1 = Path.GetFileName(Path.GetDirectoryName(path)); var folder2 = Path.GetFileName(path); uploadUrl = this.GetUploadApi(packet.FileType, folder1, folder2); } else if (packet.FileType.Equals("hpge", StringComparison.OrdinalIgnoreCase)) { var folder = DataSource.GetCurrentSid(); var param = this.GetHpGeParams(packet.Path); // "2014-07-04 00:00:00,2014-07-04 00:00:00,2014-07-04 00:00:00,PRT"; param = param.Replace('/', '-'); uploadUrl = this.GetUploadApi(packet.FileType, folder, param); } Uri uri = new Uri(this.DataCenter.GetUrl(uploadUrl)); try { using (WebClient wc = new WebClient()) { wc.UploadFileCompleted += (object sender, UploadFileCompletedEventArgs e) => { Packet p = (Packet)e.UserState; if (p != null) { if (e.Error == null) { string result = Encoding.UTF8.GetString(e.Result); this.RemovePrefix(p.Path); // LogPath.GetDeviceLogFilePath(""); string msg = string.Format("成功上传 {0}", this.GetRelFilePath(packet)); this.NotifyEvent(this, NotifyEvents.UploadFileOK, new Notify() { Message = msg }); //this.NotifyEvent(this, NotifyEvents.UploadFileOK, new PacketBase() { Message = msg }); } else { this.NotifyEvent(this, NotifyEvents.UploadFileFailed, new Notify() { Message = e.Error.Message }); } } }; wc.UploadFileAsync(uri, Post, packet.Path, packet); } } catch (WebException) { } }
private void UploadToErpHostForSupport(string filename) { WebClient myWebClient = new WebClient (); try { myWebClient.QueryString ["COMP"] = ((GlobalvarsApp)Application.Context).COMPANY_CODE; myWebClient.QueryString ["BRAN"] = ((GlobalvarsApp)Application.Context).BRANCH_CODE; myWebClient.QueryString ["USER"] = ((GlobalvarsApp)Application.Context).USERID_CODE; myWebClient.UploadProgressChanged += MyWebClient_UploadProgressChanged; myWebClient.UploadFileCompleted += MyWebClient_UploadFileCompleted; if (filename.ToLower().Contains(".zip")) { //upload zip db file and extract myWebClient.UploadFileAsync(new Uri(@"http://www.wincomcloud.com/UploadDb/uploadDbEx.aspx"), filename); }else{ //upload db file myWebClient.UploadFileAsync (new Uri(@"http://www.wincomcloud.com/UploadDb/uploadDb.aspx"), filename); } } catch { } }
public void StartUpload(int accountid, string ftpserver, string ftpusername, string ftppassword, FileInfo filetoupload, string mediatype) { try { using (webclient = new WebClient()) { ResetUpload(); CreateFTPFolders(ftpserver, ftpusername, ftppassword, accountid); webclient = new WebClient(); webclient.UploadFileCompleted += new UploadFileCompletedEventHandler(webclient_UploadFileCompleted); webclient.UploadProgressChanged += new UploadProgressChangedEventHandler(webclient_UploadProgressChanged); fileuploading = filetoupload; webclient.Credentials = new NetworkCredential(ftpusername, ftppassword); Uri uploadfile = new Uri(ftpserver + "/" + accountid.ToString() + "/" + mediatype + "/" + filetoupload.Name); webclient.UploadFileAsync(uploadfile, "STOR", filetoupload.FullName); } } catch { } }