C# Web Api 上传文件

时间:2021-07-02 07:52:31

一、 使用默认方法上传文件:

1、Action:

 /// <summary>
/// 上传文件 使用上传后的默认文件名称
/// 默认名称是BodyPart_XXXXXX,BodyPart_加Guid码
/// </summary>
/// <returns></returns>
[HttpPost, Route("Upload")]
public async Task<string> Upload()
{
try
{
//web api 获取项目根目录下指定的文件下
var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images");
var provider = new MultipartFormDataStreamProvider(root); //文件已经上传 但是文件没有后缀名 需要给文件添加后缀名
await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.FileData)
{
//这里获取含有双引号'" '
string filename = file.Headers.ContentDisposition.FileName.Trim('"');
//获取对应文件后缀名
string fileExt = filename.Substring(filename.LastIndexOf('.')); FileInfo fileinfo = new FileInfo(file.LocalFileName);
//fileinfo.Name 上传后的文件路径 此处不含后缀名
//修改文件名 添加后缀名
string newFilename = fileinfo.Name + fileExt;
//最后保存文件路径
string saveUrl = Path.Combine(root, newFilename);
fileinfo.MoveTo(saveUrl);
}
return "success";
}
catch (Exception ex)
{
throw ex;
}
}

2、html模拟代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<h1>柠檬伙伴云</h1>
<form action="/Test/Upload" method="post" enctype="multipart/form-data"> <input type="file" name="f1" /> <br /><br />
<input type="file" name="f2" /> <br /><br /> <input type="submit" value="上传图片" /> </form>
</body>
</html>

3、效果如下图:

C# Web Api 上传文件

上图就是上传后文件没有后缀名效果

C# Web Api 上传文件

对第一张没有后缀名添加后缀名的效果

二、修改上传文件后缀名

1、action:

/// <summary>
/// 上传文件 修改上传文件名称 也不包含后缀名
/// </summary>
/// <returns></returns>
[HttpPost, Route("Upload2")]
public async Task<string> Upload2()
{
try
{
//web api 获取项目根目录下指定的文件下
var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images");
//对上传文件重新命名 根据需求对应修改文件名称 不包含后缀名 只是前缀名
var provider = new RenamingMultipartFormDataStreamProvider(root); //文件已经上传 但是文件没有后缀名 需要给文件添加后缀名
await Request.Content.ReadAsMultipartAsync(provider); foreach (var file in provider.FileData)
{
//这里获取含有双引号'" '
string filename = file.Headers.ContentDisposition.FileName.Trim('"');
//获取对应文件后缀名
string fileExt = filename.Substring(filename.LastIndexOf('.')); FileInfo fileinfo = new FileInfo(file.LocalFileName);
//fileinfo.Name 上传后的文件路径 此处不含后缀名
//修改文件名 添加后缀名
string newFilename = fileinfo.Name + fileExt;
//最后保存文件路径
string saveUrl = Path.Combine(root, newFilename);
fileinfo.MoveTo(saveUrl);
}
return "success";
}
catch (Exception ex)
{
throw ex;
}
}

2、RenamingMultipartFormDataStreamProvider 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO; namespace Test.One.Common
{
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
/// <summary>
/// 文件重命名
/// </summary>
/// <param name="root"></param>
public RenamingMultipartFormDataStreamProvider(string root)
: base(root)
{
}
/// <summary>
/// 文件重命名
/// </summary>
/// <param name="headers"></param>
/// <returns></returns>
public override string GetLocalFileName(HttpContentHeaders headers)
{
string fileName = headers.ContentDisposition.Name;
if (!string.IsNullOrWhiteSpace(fileName))
{
fileName = Guid.NewGuid().ToString();
}
return fileName.Replace("\"", string.Empty);
}
}
}

3、html 模拟代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<h1>柠檬伙伴云</h1>
<form action="/Test/Upload2" method="post" enctype="multipart/form-data"> <input type="file" name="f1" /> <br /><br />
<input type="file" name="f2" /> <br /><br /> <input type="submit" value="上传图片" /> </form>
</body>
</html>

3、效果:

C# Web Api 上传文件

实例二:

api:

   /// <summary>
/// TestFile
/// </summary>
/// <returns></returns>
[HttpPost,Route("TestFile")]
public async Task<Result<bool>> TestFile()
{
Result<bool> result = new Result<bool>();
try
{
if (!Request.Content.IsMimeMultipartContent())
{
result.ReturnCode = ResultCode.InvalidParam;
result.Data = false;
result.ReturnMsg = "请求数据不是multipart/form-data类型";
return result;
} string root = HostingEnvironment.MapPath("/Resources/Templet/");
string date = DateTime.Now.ToString("yyyy-MM-dd");
string resourcePath = Path.Combine(root, date);
if (!Directory.Exists(resourcePath))
{
Directory.CreateDirectory(resourcePath);
} var provider = new RenamingMultipartFormDataStreamProvider(resourcePath);
// 接收数据,并保存文件
var bodyparts = await Request.Content.ReadAsMultipartAsync(provider); if (bodyparts.FormData.Count <= || provider.FileData == null && !provider.FileData.Any())
{
result.ReturnCode = ResultCode.InvalidParam;
result.Data = false;
result.ReturnMsg = "文件或参数不全,视频上传失败。";
return result;
} UploadContactListFileModel uploadModel = new UploadContactListFileModel(); if (bodyparts.FormData.AllKeys.Contains("ContactListName"))
{
uploadModel.ContactListName = bodyparts.FormData["ContactListName"];
} foreach (MultipartFileData file in provider.FileData)
{
//上传的文件名
string name = file.Headers.ContentDisposition.FileName.Replace("\"", "");
string extension = Path.GetExtension(name);
if (extension == ".csv" || extension == ".xls" || extension == ".xlsx")
{
//修改文件名
string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name);
string uploadPath = Path.Combine(resourcePath, newFileName);
//保存文件
File.Move(file.LocalFileName, uploadPath);
uploadModel.FilePath = uploadPath;
break;
}
}
}
catch (Exception ex)
{
result.ReturnMsg = "服务器内部发生异常";
Logger.Error("SelfsController[AddVideos]", ex);
}
return result;
}

model:

 public class UploadContactListFileModel
{ /// <summary>
/// FilePath
/// </summary>
public string FilePath { get; set; } /// <summary>
/// ContactListName
/// </summary>
public string ContactListName { get; set; } /// <summary>
/// IsError
/// </summary>
/// <returns></returns>
public bool IsError()
{
return string.IsNullOrEmpty(FilePath) || string.IsNullOrEmpty(ContactListName);
}
}

html:

  <form action="/Spread/External/TestFile" method="post" enctype="multipart/form-data">
<input type="text" name="ContactListName" value="ContactListName" /> <br />
<input type="file" name="upload" value="" /><br />
<input type="submit" name="name" value="上传" />
</form>