1. 示例代码
using System;
using System.IO;
using System.Net.Http;
/// <summary>
/// 下载文件
/// </summary>
/// <param name="serverFileName">服务器上文件名 如 close.png</param>
/// <param name="localFileName">要保存到本地的路径全名 如:C://Download/close.png</param>
/// <returns></returns>
public static bool DownLoad(string uri, string localFileName)
{
var server = new Uri(uri);
var p = Path.GetDirectoryName(localFileName);
if (!Directory.Exists(p)) Directory.CreateDirectory(p);
// 发起请求并异步等待结果
var httpClient = new HttpClient();
var responseMessage = httpClient.GetAsync(server).Result;
if (responseMessage.IsSuccessStatusCode)
{
using (var fs = File.Create(localFileName))
{
// 获取结果,并转成 stream 保存到本地。
var streamFromService = responseMessage.Content.ReadAsStreamAsync().Result;
streamFromService.CopyTo(fs);
return true;
}
}
else
return false;
}
/// <summary>
/// 通过webapi上传单张图片文件
/// </summary>
/// <param name="uploadUri">上传路径</param>
/// <param name="FullFileNames">图片文件的字节编码</param>
/// <param name="FileStars">上传文件的保存路径前缀,可null,null则不分文件夹保存</param>
/// <param name="FileNames">上传文件的保存名称</param>
/// <returns></returns>
public static List<UploadFile> UploadImageFiles(string uploadUri, byte[] FullFile, string FileStars, string FileNames)
{
// 判断传入参数是否正确
if (string.IsNullOrEmpty(uploadUri) || FullFile == null || FileNames == null)
{
Common.WriteLog.Error("上传文件时传入参数异常");
return null;
}
// 上传服务uri
var clineturi = new Uri(uploadUri);
using (var client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, 0, 0, Common.RESTTimeOut);
// 以MultipartFormData格式上传
using (var content = new MultipartFormDataContent())
{
// 文件往content添加一条ByteArrayContent
// 发送二进制内容
var fileContent = new ByteArrayContent(FullFile);
// 设置上传后保存的前缀路径和文件名称(文件名称如果重复会特殊处理)
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
if (FileStars != null) fileContent.Headers.ContentDisposition.FileNameStar = FileStars;
fileContent.Headers.ContentDisposition.FileName = FileNames;
content.Add(fileContent);
try
{
// 上传文件,获取返回的字符串内容
var result = client.PostAsync(clineturi, content).Result.Content.ReadAsStringAsync().Result;
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<UploadFile>>(result);
}
catch (Exception ex)
{
Common.WriteLog.Error(string.Format("上传文件出错!uri={0},FullFileNames={1}", uploadUri, FileStars.ToString()), ex);
return null;
}
}
}
}
2. Http 系列
2.1 发起请求
使用 HttpWebRequest 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501036.html
使用 WebClient 发起 Http 请求 :https://www.cnblogs.com/MichaelLoveSna/p/14501582.html
使用 HttpClient 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501592.html
使用 HttpClient 发起上传文件、下载文件请求:https://www.cnblogs.com/MichaelLoveSna/p/14501603.html
2.2 接受请求
使用 HttpListener 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501628.html
使用 WepApp 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501612.html
使用 WepApp 处理文件上传、下载请求:https://www.cnblogs.com/MichaelLoveSna/p/14501616.html