本文整理汇总了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("口令验证失败!");
}
}
示例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);
}
示例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);
}
示例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;
}
}
}
示例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();
}
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
}
示例10: UpLoadImage
public void UpLoadImage(string fileName)
{
WebClient wc = new WebClient();
wc.UploadFileCompleted += UploadImageRequestCompleted;
wc.UploadFileAsync(new Uri(UploadImageUrl), fileName);
}
示例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);
}
示例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)
{
}
}
示例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)
{
}
}
示例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());
}
示例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;
}
}