C#WebApi上传⽂件⼀、使⽤默认⽅法上传⽂件:
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)
{
//这⾥获取含有双引号'" '
getsavefilename
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="/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、效果如下图:
上图就是上传后⽂件没有后缀名效果
对第⼀张没有后缀名添加后缀名的效果
⼆、修改上传⽂件后缀名
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="/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、效果:
实例⼆:
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 <= 0 || 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>
PS:碰到 “MIME 多节流出现意外的结尾。MIME 多节消息不完整”
<input type="file" id="fileInput" name="fileInput"/>
input[type] 必须有name属性。
<input type="file" id="fileInput" name="fileInput"/>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。