C# 应用 - 使用 WepApp 处理文件上传、下载请求
1. 代码
/// <summary>
/// 文件上传下载控制器
/// </summary>
public class FileController : ApiController
{
/// <summary>
/// 上传文件
/// </summary>
/// http://192.168.11.67:8077/file
/// <returns></returns>
[HttpPost]
public Task<IList<UploadFile>> Upload()
{
// 获取请求客户端的IP地址
var ipAddr = GetRemoteClientIPAddress();
try
{
//如果文件路径不存在,创建路径
if (!Directory.Exists(UploadFolder)) Directory.CreateDirectory(UploadFolder);
if (Request.Content.IsMimeMultipartContent())
{
// 读取文件数据
var task = Request.Content.ReadAsMultipartAsync().ContinueWith(t =>
{
// 如果上传过程失败或被取消,则返回错误信息
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, "上传过程出错或被取消"));
}
try
{
// 读取请求数据
var provider = t.Result;
IList<UploadFile> files = new List<UploadFile>();
// 有可能一次上传多个文件,循环保存文件
foreach (var filecontent in provider.Contents)
{
// 读取文件对应的byte数组
var byteArray = filecontent.ReadAsByteArrayAsync().Result;
// 获取文件信息
var fileinfo = GetFileInfo(filecontent, byteArray.Length);
// 保存文件
if (fileinfo.StatusCode == 1)
{
fileinfo.StatusCode = FileHelper.WriteFile(fileinfo.UploadPath, byteArray, fileinfo.UploadName) ? 1 : 0;
}
// 记录文件信息
files.Add(fileinfo);
if (fileinfo.StatusCode == 1)
{
Trace.WriteLine("客户端【" + ipAddr + "】请求上传文件" + fileinfo.UploadPath + "/" + fileinfo.UploadName + "成功");
WriteLog.WriteLogger.Info("客户端【" + ipAddr + "】请求上传文件" + fileinfo.UploadPath + "/" + fileinfo.UploadName + "成功");
}
else
{
Trace.WriteLine("客户端【" + ipAddr + "】请求上传文件" + fileinfo.UploadPath + "/" + fileinfo.UploadName + "失败");
WriteLog.WriteLogger.Info("客户端【" + ipAddr + "】请求上传文件" + fileinfo.UploadPath + "/" + fileinfo.UploadName + "成功");
}
}
return files;
}
catch (Exception ex)
{
Trace.WriteLine("客户端【" + ipAddr + "】上传文件失败!");
WriteLog.WriteLogger.Error("客户端【" + ipAddr + "】上传文件失败!", ex);
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
}
});
return task;
}
else
{
// 请求格式错误
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, "请求内容格式不正确!"));
}
}
catch (Exception ex)
{
Trace.WriteLine("客户端【" + ipAddr + "】上传文件失败!");
WriteLog.WriteLogger.Error("客户端【" + ipAddr + "】上传文件失败!", ex);
// 返回异常到请求端
if (ex is HttpResponseException) throw ex; else throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
}
}
/// <summary>
/// 下载文件 注意:加上 attachment 这个header,在浏览器访问 url 链接时会弹出下载框
/// http://192.168.11.67:8077/file?name=filename
/// </summary>
/// <param name="name">文件相对路径</param>
/// <returns></returns>
[HttpGet]
public HttpResponseMessage Download(string name)
{
// 客户端请求IP
var ipAddr = GetRemoteClientIPAddress();
var result = new HttpResponseMessage();
// 读取文件
FileInfo file = new FileInfo(Path.Combine(UploadFolder, name.TrimStart('/', '\\')));
if (file.Exists)
{
var isImg = IsImage(name);
// 如果是图片,返回流,否则弹出下载框下载文件
if (isImg)
{
try
{
// 返回图片流
result.StatusCode = HttpStatusCode.OK;
result.Content = new StreamContent(new MemoryStream(File.ReadAllBytes(file.FullName)));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/" + name.Substring(name.LastIndexOf('.') + 1));
Trace.WriteLine("客户端【" + ipAddr + "】请求访问图片【" + name + "】成功");
WriteLog.WriteLogger.Info("客户端【" + ipAddr + "】请求访问图片【" + name + "】成功");
}
catch (Exception ex)
{
result.StatusCode = HttpStatusCode.InternalServerError;
Trace.WriteLine("客户端【" + ipAddr + "】请求访问图片【" + name + "】失败");
WriteLog.WriteLogger.Error("客户端【" + ipAddr + "】请求访问图片【" + name + "】失败!", ex);
}
}
else
{
try
{
// 返回文件流
FileStream fs = new FileStream(file.FullName, FileMode.Open);
result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(fs);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// 加上attachment,浏览器会自动弹出下载框
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = file.Name;
//fs.Close();
Trace.WriteLine("客户端【" + ipAddr + "】请求下载文件【" + name + "】成功");
WriteLog.WriteLogger.Info("客户端【" + ipAddr + "】请求下载文件【" + name + "】成功");
}
catch (Exception ex)
{
result = new HttpResponseMessage(HttpStatusCode.InternalServerError);
Trace.WriteLine("客户端【" + ipAddr + "】请求下载文件【" + name + "】失败");
WriteLog.WriteLogger.Error("客户端【" + ipAddr + "】请求下载文件【" + name + "】失败!", ex);
}
}
}
else
{
result.StatusCode = HttpStatusCode.NotFound;
result.Content = new StringContent("找不到文件:" + name);
Trace.WriteLine("服务器上查找不到名为【" + name + "】的文件");
WriteLog.WriteLogger.Info("服务器上查找不到名为【" + name + "】的文件");
}
return result;
}
/// <summary>
/// 上传存储文件夹
/// </summary>
private string UploadFolder = System.Configuration.ConfigurationManager.AppSettings.Get("FileSaveFolder");
/// <summary>
/// 图片后缀
/// </summary>
private string[] PicSuffixArray = { "png", "jpg", "jpeg" };
/// <summary>
/// 返回文件上传时的文件信息
/// </summary>
/// <param name="content">请求标头</param>
/// <param name="sizelength">文件字节流长度</param>
/// <returns></returns>
[NonAction()]
public UploadFile GetFileInfo(HttpContent content, int sizelength)
{
try
{
// 文件保存路径(源路径+前缀路径)
string savepath = UploadFolder;
string filenamestar = "";
if (!string.IsNullOrEmpty(content.Headers.ContentDisposition.FileNameStar))
{
filenamestar = content.Headers.ContentDisposition.FileNameStar.TrimStart('/', '\\').Trim(Path.GetInvalidPathChars());
savepath = Path.Combine(savepath, filenamestar);
}
// 文件名
string filename;
if (!string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName))
{
filename = content.Headers.ContentDisposition.FileName.TrimStart('/', '\\').Trim(Path.GetInvalidFileNameChars());
}
else
{
filename = Guid.NewGuid().ToString();
}
while (File.Exists(Path.Combine(savepath, filename)))
{
// 文件名重复在后面增加日期
filename = filename.Insert(filename.LastIndexOf('.'), "_" + DateTime.Now.ToString("yyyyMMdd"));
}
// 计算文件大小
var size = string.Empty;
if (sizelength > 1024 * 1024)
{
size = (sizelength * 100 / 1024 / 1024 / 100.00).ToString() + "MB";
}
else
{
if (sizelength > 1024)
{
size = (sizelength * 100 / 1024 / 100.00).ToString() + "KB";
}
else
{
size = sizelength.ToString() + "B";
}
}
return new UploadFile(savepath, filename, string.Format("?name={0}", Path.Combine(filenamestar, filename)), size);
}
catch (Exception ex)
{
WriteLog.WriteLogger.Error("上传文件时获取文件信息失败!", ex);
return new UploadFile("", "", "上传失败", "", 1);
}
}
/// <summary>
/// 判断是否为图片
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[NonAction()]
private bool IsImage(string fileName)
{
bool result = false;
try
{
fileName = fileName.ToLower();
var suffix = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (PicSuffixArray.Where(x => x == suffix.ToLower()).Count() > 0)
{
result = true;
}
}
catch (Exception ex)
{
WriteLog.WriteLogger.Error("判断文件" + fileName + "是否图片", ex);
}
return result;
}
/// <summary>
/// 获取请求客户的 ip 地址
/// </summary>
/// <returns></returns>
[NonAction()]
private string GetRemoteClientIPAddress()
{
var result = string.Empty;
try
{
if (Request.Properties.ContainsKey("MS_OwinContext"))
result = ((OwinContext)Request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
}
catch(Exception ex)
{
WriteLog.WriteLogger.Error("获取请求客户的 ip 地址出错!", ex);
}
return result;
}
}
/// <summary>
/// 上传文件信息
/// </summary>
public class UploadFile
{
/// <summary>
///
/// </summary>
/// <param name="name">上传时的文件原名</param>
/// <param name="paramurl">上传后访问路径</param>
/// <param name="size">文件大小</param>
/// <param name="namestar">存储的文件路径</param>
public UploadFile(string path, string name, string paramurl, string size, int statuscode = 1)
{
UploadPath = path;
UploadName = name;
ParamUrl = paramurl;
Size = size;
StatusCode = statuscode;
}
/// <summary>
/// 上传文件结果,1是成功
/// </summary>
public int StatusCode { get; set; }
/// <summary>
/// 上传时的文件前缀路径
/// </summary>
public string UploadPath { get; set; }
/// <summary>
/// 上传时的文件名
/// </summary>
public string UploadName { get; set; }
/// <summary>
/// 文件访问的路径参数
/// </summary>
public string ParamUrl { get; set; }
/// <summary>
/// 文件大小
/// </summary>
public string Size { get; set; }
}
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