OWIN+WebAPI上传文件
一、问题描述
之前文件上传的实现一直用的是ASP.NET.MVC.Controller,通过继承MVC.Controller 使用其中的Request来实现文件上传,代码如下:
后来因为种种原因需要将框架改成ASP.NET API的方式,此时Controller继承的是ApiController,ApiController里面的Request并不可以获取请求的Form表单也无法获取请求的文件,故此方法行不通,需要另寻他法。

二、解决方法
通过查询资料,发现如下方法可以解决以上问题
1、首先将之前通过Form表单传递的数据,改成使用Uri参数的方式传递
2、实例化类MultipartFormDataStreamProvide,MultipartFormDataStreamProvider类
如下是类的官方解释:An IMultipartStreamProvider suited for use with HTML file uploads for writing file content to a FileStream.
3、将Request的内容写入到Provider中,载入文件到本地存储
await Request.Content.ReadAsMultipartAsync(provider);
4、通过Provider.FileData循环获取每个文件Data
5、获取文件名并对其进行处理
string originalName = file.Headers.ContentDisposition.FileName;
if (originalName.StartsWith("\"") && originalName.EndsWith("\""))
{//去掉头尾的引号
originalName = originalName.Trim('"');
}
if (originalName.Contains(@"/") || originalName.Contains(@"\"))
{//将其改成斜杠改成规范的文件目录格式
originalName = Path.GetFileName(originalName);
}
6、将临时文件保存在本地
/// <summary>
/// 上传文件到文件服务器
/// </summary>
/// <param name="destPathID">目标文件夹路径</param>
/// <returns></returns>
[HttpPost]
public async Task<IHttpActionResult> UploadFileToDS([FromUri] string uploadDSDestPathID)
{//上传还有问题
//应该默认覆盖
JsonMessage jsonMessage = new JsonMessage();
LogHelper.WriteInfoLog($"调用UploadFileToDS,uploadDSDestPathID:{uploadDSDestPathID}");
try
{
//从Form中获取上传的路径;
string destFolder = DNCFileRootPath + uploadDSDestPathID.Replace("replace_lp", @"\").Replace("replace_dup", ":");
if (Directory.Exists(destFolder))
{
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartFormDataStreamProvider(DNCFileRootPath);//应该是创建了一个临时文件
/// 载入文件在本地存储
await Request.Content.ReadAsMultipartAsync(provider);
/// 检查是否存在有效的文件
if (provider.FileData.Count == 0)
return BadRequest();
foreach (MultipartFileData file in provider.FileData)
{
string originalName = file.Headers.ContentDisposition.FileName;
if (originalName.StartsWith("\"") && originalName.EndsWith("\""))
{
originalName = originalName.Trim('"');
}
if (originalName.Contains(@"/") || originalName.Contains(@"\"))
{
originalName = Path.GetFileName(originalName);
}
string destPath = Path.Combine(destFolder, originalName);
if (File.Exists(destPath))
{//如果文件存在则删除,相当于自动覆盖
File.Delete(destPath);
}
File.Move(file.LocalFileName, Path.Combine(destFolder, originalName));
}
jsonMessage.type = 1;
jsonMessage.message = "操作成功";
}
else
{//目标路径不存在
jsonMessage.type = 2;
jsonMessage.message = "上传失败,目标文件夹不存在!" + destFolder;
LogHelper.WriteErrorLog($"调用UploadFileToDS方法失败" + jsonMessage.message, true);
}
}
catch (Exception ex)
{
jsonMessage.type = -1;
jsonMessage.message = "上传失败!";
LogHelper.WriteErrorLog($"调用UploadFileToDS方法失败" + ex.Message, true);
}
return Ok(jsonMessage);
}

浙公网安备 33010602011771号