上网搜了下Web Api上传文件的功能,发现都写的好麻烦,就自己写了一个,比较简单,直接上传文件就可以,可以用Postman测试。

简单的举例

/// <summary>
/// 超级简单的文件上传
/// </summary>
public class EasyUploadFileController : ApiController
{
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
[HttpPost]
public string PostWithFile()
{
UploadWithFile(HttpContext.Current.Request);
return "文件上传成功";
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="request"></param>
private void UploadWithFile(HttpRequest request)
{
for (int i = ; i < request.Files.Count; i++)
{
var file = request.Files[i];
if (file.ContentLength <= ) continue;
var ext = new FileInfo(file.FileName).Extension;
var fullPath = Path.Combine(@"G:\Image", Path.GetFileName(Guid.NewGuid() + ext));
file.SaveAs(fullPath);
}
} }

结果

复杂举例带参数

public class UploadFileController : ApiController
{
/// <summary>
/// 8M
/// </summary>
public const int MAX_LENGTH = * * ;
public const int MIN_WIDTH = ;
public const int MIN_HEIGHR = ; /// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
[HttpPost]
public string PostWithFile()
{
JObject jObject = GetParam(HttpContext.Current.Request);
ParamModel model = GetParamModel(jObject); Tuple<bool, string> upload = UploadWithFile(HttpContext.Current.Request);
return upload.Item2 + " 参数:" + JsonConvert.SerializeObject(model);
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="request"></param>
private Tuple<bool, string> UploadWithFile(HttpRequest request)
{
bool success = true;
string message = string.Empty;
for (int i = ; i < request.Files.Count; i++)
{
var file = request.Files[i];
if (file.ContentLength <= ) continue; #region check的代码
if (!FitFileLength(file))
{
message = message + file.FileName + "文件大小不能超过8M;";
continue;
} if (!FitImageSize(file))
{
message = message + file.FileName + "图片长宽分别不能小于600像素;";
continue;
}
#endregion var ext = new FileInfo(file.FileName).Extension;
var fullPath = Path.Combine(@"G:\Image", Path.GetFileName(Guid.NewGuid() + ext));
file.SaveAs(fullPath);
} if (string.IsNullOrEmpty(message))
{
message = "上传成功";
}
Tuple<bool, string> result = new Tuple<bool, string>(success, message);
return result;
} /// <summary>
/// 符合文件大小
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private bool FitFileLength(HttpPostedFile file)
{
bool result = true;
if (file.ContentLength >= MAX_LENGTH)
{
result = false;
}
return result;
} /// <summary>
/// 符合图片尺寸
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private bool FitImageSize(HttpPostedFile file)
{
bool result = true;
var ext = new FileInfo(file.FileName).Extension;
if (IsImage(ext))
{
Image image = Image.FromStream(file.InputStream);
if (image.Height <= MIN_HEIGHR || image.Width <= MIN_WIDTH)
{
result = false;
}
} return result;
} /// <summary>
/// 监测是否是图片
/// </summary>
/// <param name="ext"></param>
/// <returns></returns>
public bool IsImage(string ext)
{
bool result = false;
switch (ext.ToLower())
{
case (".jpg"):
case (".png"):
case (".gif"):
case (".bmp"):
result = true;
break;
default:
result = false;
break;
}
return result;
} /// <summary>
/// 获得参数
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
private JObject GetParam(HttpRequest request)
{
JObject jObject = new JObject();
foreach (string key in request.Form)
{
jObject[key] = request.Form[key];
}
return jObject;
} /// <summary>
/// 简单的Model转换
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
private ParamModel GetParamModel(JObject jObject)
{
ParamModel model = new ParamModel();
model.Param1 = jObject["Param1"] != null ? jObject["Param1"].ToString() : "";
model.Param2 = jObject["Param2"] != null ? jObject["Param2"].ToString() : "";
model.Param3 = jObject["Param3"] != null ? jObject["Param3"].ToString() : ""; return model;
}
}

Html测试

<div class="jumbotron">
<form action="/UploadFile/PostWithFile" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group">
<label for="Param1" class="col-xs-2">Param1</label>
<input type="text" class="form-control col-xs-8" name="Param1" placeholder="Param1">
</div>
<div class="form-group">
<label for="Param2" class="col-xs-2">Param2</label>
<input type="text" class="form-control" name="Param2" placeholder="Param2">
</div>
<div class="form-group">
<label for="Param3" class="col-xs-2">Param3</label>
<input type="text" class="form-control" name="Param3" placeholder="Param3">
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-xs-2">File input</label>
<input type="file" name="f1" />
<input type="file" name="f2" />
<input type="file" name="f3" />
</div>
<button type="submit" class="btn btn-default">上传图片</button>
</form>
</div>

源码

https://github.com/jasonhua95/WebApiUploadFile.git

WebApi上传文件的更多相关文章

  1. Owin WebAPI上传文件

    Owin是微软出了几年的东东了,一直没时间学习.大概了解了下,是一个脱离IIS环境,快速搭建WebAPI服务的东西. 刚好想尝试下尽量脱离IIS创建简单快捷配置的项目,就是用了Nginx+Owin的模 ...

  2. Asp.Net Core WebApi 和Asp.Net WebApi上传文件

    public class UpLoadController : ControllerBase { private readonly IHostingEnvironment _hostingEnviro ...

  3. webAPI 上传文件 404错误(转载)

    webAPI文件上传时文件过大404错误的问题  来源:https://www.cnblogs.com/dzhengyang/p/9149157.html 背景:最近公司有个需求,外网希望自动保存数据 ...

  4. .Net Core2.2 WebApi上传文件

    基于.net core2.2的webapi程序,接收客户端上传的文件.按照以下写法,file的值永远是null [HttpPost] public void Post([FromForm] IForm ...

  5. C# WebApi 上传文件

    本文转载自:http://www.cnblogs.com/zj1111184556/p/3494502.html public class FileUploadController : ApiCont ...

  6. (转)WebApi 上传文件

    本文转载自:http://www.cnblogs.com/zj1111184556/p/3494502.html public class FileUploadController : ApiCont ...

  7. 使用swagger上传文件

    经常使用swagger,可以通过设置[ProducesResponseType]标记接口的返回信息:swagger也能通过接口的参数列表,自动获得发送的数据结构信息. 不过有一个例外,就是上传文件的时 ...

  8. webApi上传下载文件

    上传文件通过webApi html端调用时包含(form提交包含 enctype="multipart/form-data",才可以启作用获取到文件) public class U ...

  9. WebAPI通过multipart/form-data方式同时上传文件以及数据(含HttpClient上传Demo)

    简单的Demo,用于了解WebAPI如何同时接收文件及数据,同时提供HttpClient模拟如何同时上传文件和数据的Demo,下面是HttpClient上传的Demo界面 1.HttpClient部分 ...

随机推荐

  1. Spring Boot/Spring Cloud

    104.什么是 spring boot?         在Spring框架这个大家族中,产生了很多衍生框架,比如 Spring.SpringMvc框架等,Spring的核心内容在于控制反转(IOC) ...

  2. 3.1 MathType上标位置调整的两种方法

    具体操作步骤如下: 1.打开MathType窗口后在工作区域中编辑好公式. 2.调整上标位置有两种方法: (1)选中要调整的上标,按下“Ctrl+↑,Ctrl+↓,Ctrl+←,Ctrl+→”进行调整 ...

  3. pycharm 3.4 破解

    修改host,增加一行: 0.0.0.0 account.jetbrains.com 使用Activate code注册: EB101IWSWD-eyJsaWNlbnNlSWQiOiJFQjEwMUl ...

  4. Parallel Programming for FPGAs 学习笔记(1)

    Parallel Programming for FPGAs 学习笔记(1)

  5. Maya中输出alembic文件的方法

    Maya中输出alembic文件是有现成api调用的,与maya中大部分api一样,这个功能参数的传入是非常类似mel的,本质上讲都是kwargs类型的参数,所以我们传入的参数就需要整理成类似于mel ...

  6. Linux centos7. 配置安装Oracle

    oralcle 11g r2 配置一下前期的网络环境 一 修改linux核心配置 1.修改用户的SHELL限制vi /etc/security/limits.conf oracle soft npro ...

  7. linux SVN命令

    1.将文件checkout到本地目录 svn checkout path(path是服务器上的目录)   例如:svn checkout svn://192.168.1.1/pro/domain    ...

  8. 解决双击excel文件打开多个excel.exe进程的问题

    解决双击excel文件打开多个excel.exe进程的问题有些时候,双击两个excel文件,会打开多个excel进程,不同进程之间不能复制粘贴公式,只能粘贴数值,很不方便.怎么样双击多个excel文件 ...

  9. node升级的正确方法

    本文主要是针对安装了node的用户如何对node进行升级或者安装指定版本:没有安装node的可以参考连接node安装方法 . 安装方法: 1.产看node版本,没安装的请先安装: $  node -v ...

  10. 虚拟机克隆之后,网卡名称从eth0变成eth1之后的解决办法

    使用VMware安装了CentOS虚拟机,克隆之后使用service network restart指令来重新启动网络服务时,会看到有eth0网卡不存在的提示.出现这种现象的原因是,很多Linux d ...