本文整理汇总了C#中System.Net.WebClient.UploadFile方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.UploadFile方法的具体用法?C# WebClient.UploadFile怎么用?C# WebClient.UploadFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebClient
的用法示例。
在下文中一共展示了WebClient.UploadFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: UploadToErpHostForSupport
private static 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;
if (filename.ToLower().Contains(".zip"))
{
//upload zip db file and extract
byte[] responseArray = myWebClient.UploadFile (@"http://www.wincomcloud.com/UploadDb/uploadDbEx.aspx", filename);
}else{
//upload db file
byte[] responseArray = myWebClient.UploadFile (@"http://www.wincomcloud.com/UploadDb/uploadDb.aspx", filename);
}
} catch {
}
finally{
try{
File.Delete (filename);
}catch
{}
}
}
示例2: Convert
public bool Convert(string sourceFilePath, int sourceFormat, string targetFilePath, int targetFormat)
{
// Restrict supported conversion to only regular-pdf -> docx,
// but don't forget that CloudConvert supports almost anything.
if (sourceFormat != (int)FileTypes.pdf || targetFormat != (int)FileTypes.docx || IsScannedPdf(sourceFilePath))
{
return false;
}
// Execute the call
using (WebClient client = new WebClient())
{
// Send the file to CloudConvert
client.Headers["Content-Type"] = "binary/octet-stream";
string address = string.Format("{0}?apikey={1}&input=upload&inputformat={2}&outputformat={3}&file={4}",
"https://api.cloudconvert.com/convert",
CloudConverterKey,
"pdf",
"docx",
HttpUtility.UrlEncode(sourceFilePath));
byte[] response = client.UploadFile(address, sourceFilePath);
// Save returned converted file
File.WriteAllBytes(targetFilePath, response);
}
// Everything ok, return the success to the caller
return true;
}
示例3: create
// Method to create questionlist by serializing object and sending it to the API,
// Icon gets sent to API by saving it to the a temporary cache folder in order to send it to the API
public int create(Questionlist questionlist)
{
if(questionlist.icon != null)
{
string url = @"../../Cache/"+questionlist.icon;
try
{
if (questionlist.image != null)
{
questionlist.image.Save(url);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
using (var client = new WebClient())
{
client.UploadFile(bc.url+"/questionlist/uploadicon", "POST", url);
}
}
var result = bc.jsonRequest("/questionlist/create", bc.serialize.Serialize(questionlist));
if (result != null)
{
Questionlist list = bc.serialize.Deserialize<Questionlist>(result);
return list.id;
}
else
{
return 0;
}
}
示例4: UpLoadMediaFile
/// <summary>
/// 上传本地文件
/// </summary>
/// <param name="AccessToken"></param>
/// <param name="UpLoadMediaType"></param>
/// <param name="FilePath"></param>
public static string UpLoadMediaFile(string AccessToken, string UpLoadMediaType, string FilePath)
{
//上传本地文件,用户上传的文件必须先保存在服务器中,再上传至微信接口(微信的文件保存仅3天)
//TODO 本地不想保留文件时,如何直接将用户上传的文件中转给微信?
//TODO 文件限制
/*
* 上传的多媒体文件有格式和大小限制,如下:
* 图片(image): 256K,支持JPG格式
* 语音(voice):256K,播放长度不超过60s,支持AMR\MP3格式
* 视频(video):1MB,支持MP4格式
* 缩略图(thumb):64KB,支持JPG格式
*/
string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", AccessToken, UpLoadMediaType);//接口地址及参数
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
try
{
byte[] res = client.UploadFile(url, FilePath);
//正常结果:{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
//异常结果:{"errcode":40004,"errmsg":"invalid media type"}
return Encoding.Default.GetString(res, 0, res.Length);
}
catch (Exception ex)
{
throw;
}
}
示例5: UploadImage
public static string UploadImage(string filePath)
{
if(!File.Exists(filePath))
return "Fil ikke funnet.";
var url = "http://www.jaktloggen.no/customers/tore/jalo/services/uploadimage.ashx";
using(WebClient client = new WebClient())
{
var nameValueCollection = new NameValueCollection();
nameValueCollection.Add("userid",UserId);
client.QueryString = nameValueCollection;
try
{
byte[] responseArray = client.UploadFile(url, filePath);
return Encoding.Default.GetString(responseArray);
}
catch(WebException ex)
{
Console.WriteLine(ex.Message);
}
}
return "Error";
}
示例6: Get
public string Get(string url, WebProxy proxy, string publicKey, string secretKey, string upload, string fileName = "", string fileMime = "", string fileContent = "")
{
using (var client = new WebClient())
{
if (proxy != null)
client.Proxy = proxy;
client.Encoding = Encoding.UTF8;
if (String.IsNullOrWhiteSpace(fileContent))
{
var web = url + String.Format("/resources/file?public_key={0}&secret_key={1}&file_name={2}&file_mime={3}", publicKey, secretKey, fileName, fileMime);
byte[] json = client.UploadFile(web, upload);
return Encoding.UTF8.GetString(json);
}
else
{
var web = url + String.Format("/resources/file?public_key={0}&secret_key={1}&file_name={2}&file_mime={3}", publicKey, secretKey, fileName, fileMime);
var values = new System.Collections.Specialized.NameValueCollection
{
{"file_content", fileContent}
};
return Encoding.Default.GetString(client.UploadValues(web, values));
}
}
}
示例7: Import_documents_by_csv_should_preserve_documentId_if_id_header_is_present
public void Import_documents_by_csv_should_preserve_documentId_if_id_header_is_present()
{
var databaseName = "TestCsvDatabase";
var entityName = typeof(CsvEntity).Name;
var documentId = "MyCustomId123abc";
using (var store = NewRemoteDocumentStore(false, null, databaseName))
{
var url = string.Format(@"http://localhost:8079/databases/{0}/studio-tasks/loadCsvFile", databaseName);
var tempFile = Path.GetTempFileName();
File.AppendAllLines(tempFile, new[]
{
"id,Property_A,Value,@Ignored_Property," + Constants.RavenEntityName,
documentId +",a,123,doNotCare," + entityName
});
using (var wc = new WebClient())
wc.UploadFile(url, tempFile);
using (var session = store.OpenSession(databaseName))
{
var entity = session.Load<CsvEntity>(documentId);
Assert.NotNull(entity);
var metadata = session.Advanced.GetMetadataFor(entity);
var ravenEntityName = metadata.Value<string>(Constants.RavenEntityName);
Assert.Equal(entityName, ravenEntityName);
}
}
}
示例8: Main
static void Main(string[] args)
{
// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201403/20140326
// X:\jsc.smokescreen.svn\core\javascript\com.abstractatech.analytics\com.abstractatech.analytics\ApplicationWebService.cs
// X:\jsc.svn\examples\rewrite\Test\Feature1\Feature1\Class1.cs
// "C:\util\jsc\nuget\Feature4.1.0.0.0.nupkg"
var c = new WebClient();
c.UploadProgressChanged +=
(sender, e) =>
{
Console.WriteLine(new { e.ProgressPercentage });
};
var x = c.UploadFile(
//"http://192.168.1.84:26994/upload",
"http://my.jsc-solutions.net/upload",
@"C:\util\jsc\nuget\Feature4.1.0.0.0.nupkg"
);
// Encoding.UTF8.GetString(x) "<ok>\r\n <ContentKey>2</ContentKey>\r\n</ok>" string
// Encoding.UTF8.GetString(x) "<ok><ContentKey>6</ContentKey></ok>" string
Debugger.Break();
}
示例9: Main
static void Main(string[] args)
{
var wc = new WebClient();
wc.UploadFile("http://localhost:1729/api/Bib2/UploadFile", "POST", @"C:\rest\Nowy dokument tekstowy.txt");
Console.WriteLine("Upload done");
DownloadFileAsync(@"C:\rest1\encypt", "encrypt").Wait();
Console.WriteLine("Encrypt done");
DownloadFileAsync(@"C:\rest1\decrypt.txt", "decrypt").Wait();
Console.WriteLine("Decrypt done");
Console.WriteLine("MD5 SUM:");
byte[] md5 = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=MD5");
foreach (var item in md5)
{
Console.WriteLine(item);
}
Console.WriteLine("SHA SUM");
byte[] sha = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=SHA");
foreach (var item in sha)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
示例10: Main
static void Main(string[] args)
{
int start = Environment.TickCount;
int maxParallelUploads = 50;
string urlForUploads = "http://localhost:8080";
string dirToUpload = Path.Combine(".", "default-to-upload");
if (args.Length > 0)
{
dirToUpload = args[0];
}
ParallelOptions opts = new ParallelOptions();
opts.MaxDegreeOfParallelism = maxParallelUploads;
Parallel.ForEach(Directory.EnumerateFiles(dirToUpload, "*", SearchOption.AllDirectories), opts, (filepath) =>
{
Console.WriteLine("Uploading {0} on thread {1}...", filepath, Thread.CurrentThread.ManagedThreadId);
WebClient webClient = new WebClient();
int sleepPeriodMs = 1000;
bool retry = true;
bool success = false;
while (retry)
{
retry = false;
try
{
webClient.UploadFile(urlForUploads, filepath);
success = true;
}
catch (WebException e)
{
var r = (HttpWebResponse)e.Response;
if (r != null && r.StatusCode == HttpStatusCode.ServiceUnavailable)
{
// We are overloading the server. Wait some time and try again.
Console.WriteLine("Server is overloaded. Retrying in {0}ms...", sleepPeriodMs);
Thread.Sleep(sleepPeriodMs);
sleepPeriodMs *= 2;
retry = true;
}
else
{
Console.WriteLine("Failed to upload file {0}. Error was: \n{1}.\nMoving on to next file.", filepath, e.ToString());
}
}
catch
{
Console.WriteLine("Unexpected error! Failed to upload file {0}. Moving on to next file.", filepath);
}
}
if (success)
{
// The file was successfully uploaded to the server - delete it!
File.Delete(filepath);
}
});
Console.WriteLine("Took {0} ticks to upload files.", Environment.TickCount - start);
}
示例11: Main
private static void Main(string[] args)
{
Console.Title = "Leafy Image Uploader 🍂";
Config.Init();
ShowWindow(GetConsoleWindow(), 0);
var FullName = args.FirstOrDefault();
var FileName = args.FirstOrDefault()?.Split('\\').LastOrDefault();
var FileExtension = FileName?.Split('.').LastOrDefault();
var NewFileName = DateTime.Now.ToString("dd-MMM-yy_HH:mm:ss") + "." + FileExtension;
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpAcc, ftpPass);
if (FullName != null)
client.UploadFile(ftpAddr + NewFileName, "STOR", FullName);
}
OpenClipboard(IntPtr.Zero);
if (!httpAddr.EndsWith("/"))
{
httpAddr = httpAddr + "/";
}
var URL = httpAddr + NewFileName;
Process.Start(URL);
var ptr = Marshal.StringToHGlobalUni(URL);
SetClipboardData(13, ptr);
CloseClipboard();
Marshal.FreeHGlobal(ptr);
}
示例12: downloadImage
// Bilder runterladen
public static string downloadImage(string imagePath, string id, string type, string folder, string newFilename)
{
if (String.IsNullOrEmpty(imagePath))
return "";
// Pfade und Dateiname erstellen
string link = "http://thetvdb.com/banners/" + imagePath;
string imageType = (!String.IsNullOrEmpty(type)) ? type : imagePath.Substring(0, imagePath.IndexOf("/"));
string path = "C:\\tempImages\\" + id + "\\" + imageType + "\\";
string localFilename = imagePath.Substring(imagePath.LastIndexOf("/") + 1, imagePath.Length - imagePath.LastIndexOf("/") - 1);
// Pfad prüfen und ggfl. erstellen
if (!Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
// Prüfen ob das Bild schon existiert
if (File.Exists(path + newFilename))
return path + newFilename;
// Bild runterladen
using (WebClient client = new WebClient())
{
client.DownloadFile(link, path + newFilename);
NetworkCredential cred = new NetworkCredential("olro", "123user!");
WebClient ftp = new WebClient();
ftp.Credentials = cred;
ftp.UploadFile("ftp://217.160.178.136/Images/" + folder + "/" + newFilename, path + newFilename);
}
return path + localFilename;
}
示例13: uploadFile
/// <summary>
/// 文件上传
/// </summary>
/// <param name="bucket">命名空间</param>
/// <param name="fileName">文件在OSS上的名字</param>
/// <param name="filePath">本地文件路径</param>
/// <param name="contentType">文件类型</param>
/// <returns>成功返回URL,失败返回服务器错误信息</returns>
public string uploadFile(string bucket,string fileName, string filePath,string contentType)
{
FileStream theFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
WebClient theWebClient = new WebClient();
string GMTime = DateTime.Now.ToUniversalTime().ToString("r");
MD5CryptoServiceProvider theMD5Hash = new MD5CryptoServiceProvider();
byte[] hashDatas;
hashDatas = theMD5Hash.ComputeHash(new byte[(int)theFileStream.Length]);
string contentMD5 = Convert.ToBase64String(hashDatas);
HMACSHA1 theHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(getAccessPar().key));
string headerStr = "PUT\n"+
contentMD5+"\n"+
contentType+"\n"+
GMTime+"\n"+
"x-oss-date:"+GMTime+"\n"+
bucket+ fileName;
byte[] rstRes = theHMACSHA1.ComputeHash(Encoding.Default.GetBytes(headerStr));
string strSig = Convert.ToBase64String(rstRes);
theWebClient.Headers.Add(HttpRequestHeader.Authorization,"OSS "+getAccessPar().id+":"+strSig);
theWebClient.Headers.Add(HttpRequestHeader.ContentMd5, contentMD5);
theWebClient.Headers.Add(HttpRequestHeader.ContentType, contentType);
theWebClient.Headers.Add("X-OSS-Date", GMTime);
try
{
byte[] ret = theWebClient.UploadFile("http://storage.aliyun.com/" +bucket+ fileName, "PUT", filePath);
string strMessage = Encoding.ASCII.GetString(ret);
return "http://storage.aliyun.com" +bucket+ fileName;
}
catch (WebException e)
{
Stream stream = e.Response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
}
示例14: Main
static void Main(string[] args)
{
string folder = ConfigurationManager.AppSettings["SaveFolder"];
using (var db = new FacilityReservationKioskEntities())
{
var camera = db.Cameras.ToList();
foreach(var cam in camera)
{
try
{
string fileName = folder + "image-" + cam.CameraID + ".jpg";
WebClient client = new WebClient();
client.DownloadFile("http://" + cam.IPAddress + "/snap.jpg?JpegSize=L",fileName);
WebClient wc = new WebClient();
wc.UploadFile("http://crowd.sit.nyp.edu.sg/FRSIpad/UploadPicture.aspx", fileName);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
示例15: Main
// {url} {file} {teamName} {password}
static void Main(string[] args)
{
if (args.Length != 4)
{
Console.WriteLine("Usage: Compete.Uploader {url} {dll} {teamName} {password}");
Environment.Exit(1);
}
Console.WriteLine("Uploading...");
var client = new WebClient();
try
{
client.UploadFile(String.Format("{0}/UploadBot?teamName={1}&password={2}", args[0], args[2], args[3]), "post", args[1]);
}
catch (Exception err)
{
Console.WriteLine("Couldn't upload, uploads may be disabled. Also, check your username and password");
Console.WriteLine("");
Console.WriteLine("");
Console.Error.WriteLine("FAIL: " + err);
Environment.Exit(1);
}
Console.WriteLine("Done, Good Luck!");
}