当前位置: 首页>>代码示例>>C#>>正文


C# WebClient.UploadFileAsync方法代码示例

本文整理汇总了C#中System.Net.WebClient.UploadFileAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.UploadFileAsync方法的具体用法?C# WebClient.UploadFileAsync怎么用?C# WebClient.UploadFileAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


在下文中一共展示了WebClient.UploadFileAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: skinButton1_Click

        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://clouduser:" + keyword.ToString() + "@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("口令验证失败!");
            }
        }
开发者ID:corerman,项目名称:FTP-Cloud-Upload-,代码行数:31,代码来源:Form1.cs

示例2: UploadFile

 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);
 }
开发者ID:daralbrecht,项目名称:PDFAsystent,代码行数:8,代码来源:UploadForm.cs

示例3: CloudUploader_Load

 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);
 }
开发者ID:ngonzalezromero,项目名称:wwt-windows-client,代码行数:13,代码来源:CloudUploader.cs

示例4: UploadFile

 /// <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;
         }
     }
 }
开发者ID:djdino56,项目名称:ICT4Events-Web,代码行数:23,代码来源:FTPHelper.cs

示例5: btn_Upload_Click

        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();
            }
        }
开发者ID:berryzed,项目名称:Http-File-Upload-Exam,代码行数:44,代码来源:MainForm.cs

示例6: PostFileUploadRequest

        /// <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;
        }
开发者ID:JPaulDuncan,项目名称:Scribd.Net,代码行数:72,代码来源:Service.cs

示例7: UploadFileAsync

        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);
        }
开发者ID:mrinalinigarg,项目名称:cross-copy,代码行数:32,代码来源:Server.cs

示例8: doUpload


//.........这里部分代码省略.........

            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);
        }
开发者ID:Sadeghi85,项目名称:eShiaWord2HtmlClient,代码行数:101,代码来源:Form1.cs

示例9: Perform

        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);
            }
        }
开发者ID:ChristianJaspers,项目名称:saapp-ios,代码行数:35,代码来源:FileUploadRequest.cs

示例10: UpLoadImage

 public void UpLoadImage(string fileName)
 {
     WebClient wc = new WebClient();
     wc.UploadFileCompleted += UploadImageRequestCompleted;
     wc.UploadFileAsync(new Uri(UploadImageUrl), fileName);
 }
开发者ID:minhle2994,项目名称:SOA-LibraryManagement,代码行数:6,代码来源:EditBook.xaml.cs

示例11: SubmitFile

 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);
 }
开发者ID:vaginessa,项目名称:cameyo,代码行数:12,代码来源:PkgCreateWin.xaml.cs

示例12: SendFilePacket

        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)
            {

            }
        }
开发者ID:mrddos,项目名称:planisphere,代码行数:27,代码来源:Agent.cs

示例13: SendFilePacket

        /// <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)
            {
             
            }
        }
开发者ID:oisy,项目名称:scada,代码行数:66,代码来源:DataAgent.cs

示例14: buttonReport_Click

        //--------------------//

        #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());
        }
开发者ID:nano-byte,项目名称:common,代码行数:16,代码来源:ErrorReportForm.cs

示例15: UpLoadImage

 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;
     }
 }
开发者ID:minhle2994,项目名称:SOA-LibraryManagement,代码行数:17,代码来源:AddBook.xaml.cs


注:本文中的System.Net.WebClient.UploadFileAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。