1.5 WEB API 上传文件

时间:2023-02-04 08:42:52

1.前提,设置跨域

2.在控制器头添加允许跨域

  /// <summary>
/// 文件管理口控制器
/// </summary>
[EnableCors("*", "*", "*")]
[RoutePrefix("File")]
public class FileController

3.上传方法

  /// <summary>
/// 图片上传 [FromBody]string token
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("Upload/ImgUpload")]
public ResponseModel ImgUpload()
{
ResponseModel response = new ResponseModel();
// 文件保存目录路径
const string saveTempPath = "~/UploadFiles/";
if (!Directory.Exists(HttpContext.Current.Server.MapPath(saveTempPath)))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(saveTempPath));
}
HttpFileCollection files = HttpContext.Current.Request.Files;
const string fileTypes = "gif,jpg,jpeg,png,bmp";
foreach (string key in files.AllKeys)
{
HttpPostedFile file = files[key];//file.ContentLength文件长度 if (file.ContentLength > AllConfig.CommonStaticConfigInfo.MaxFileSize * 1024)
{
response.Fail("上传文件大小超过限制。");
return response;
}
else
{
var fileExt = file.FileName.Substring(file.FileName.LastIndexOf('.')); if (String.IsNullOrEmpty(fileExt) ||
Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
{
response.Fail("不支持上传文件类型。");
return response;
}
else
{
if (string.IsNullOrEmpty(file.FileName) == false)
file.SaveAs(HttpContext.Current.Server.MapPath(saveTempPath) + file.FileName);
}
}
}
return response;
}

ResponseModel是自己实现的,有兴趣也可以看看,返回自己实现吧。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Model
{
/// <summary>
/// 响应参数父级类型
/// </summary>
public class ResponseModel
{ /// <summary>
/// 构造
/// </summary>
public ResponseModel()
{
State = (int)RequestStateEnum.Success;
Msg = "成功";
}
/// <summary>
/// 构造
/// </summary>
/// <param name="state">请求状态</param>
/// <param name="callback">透传字段</param>
/// <param name="postTime">请求时间</param>
/// <param name="msg">返回信息</param>
public ResponseModel(RequestStateEnum state, string callback, string postTime, string msg)
{
State = (int)state;
Callback = callback;
PostTime = postTime;
Msg = msg;
}
/// <summary>
/// 构造
/// </summary>
/// <param name="callback">透传字段</param>
/// <param name="postTime">请求时间</param>
/// <param name="msg">返回信息</param>
public ResponseModel(string callback, string postTime, string msg)
{
State = (int)RequestStateEnum.Success;
Callback = callback;
PostTime = postTime;
Msg = msg;
}
/// <summary>
/// 构造
/// </summary>
/// <param name="callback">透传字段</param>
/// <param name="postTime">请求时间</param>
public ResponseModel(string callback, string postTime)
{
State = (int)RequestStateEnum.Success;
Callback = callback;
PostTime = postTime;
Msg = "成功";
}
/// <summary>
/// 请求状态
/// </summary>
public int State { get; protected set; }
/// <summary>
/// 透传字段
/// </summary>
public string Callback { get; set; } /// <summary>
/// 请求时间
/// </summary>
public string PostTime { get; set; } /// <summary>
/// 返回信息
/// </summary>
public string Msg { get; protected set; } /// <summary>
/// 错误
/// </summary>
/// <param name="msg"></param>
/// <param name="state"></param>
public void Fail(string msg, RequestStateEnum state = RequestStateEnum.Error)
{
Msg = msg;
State = (int)state;
}
/// <summary>
/// 错误,根据错误短语获取错误详细描述
/// </summary>
/// <param name="shortMsg">错误短语</param>
public void Fails(string shortMsg)
{
Msg = AllMsg.GetMsg(shortMsg);
State = (int)RequestStateEnum.Error;
} /// <summary>
/// 系统级错误
/// </summary>
/// <param name="msg"></param>
public void SystemErr(string msg)
{
Msg = msg;
State = (int)RequestStateEnum.SystemErr;
} /// <summary>
/// 成功
/// </summary>
/// <param name="msg"></param>
/// <param name="state"></param>
public void Success(string msg, RequestStateEnum state = RequestStateEnum.Success)
{
this.Msg = msg;
State = (int)RequestStateEnum.Success;
}
/// <summary>
/// 未登录验证
/// </summary>
public void NeedLogin()
{
this.Msg = "请登录系统后再进行操作!";
State = (int)RequestStateEnum.NeedLogin;
}
private string RealName;
public void SetRealName(string realName)
{
RealName = realName;
} public string GetRealName() { return RealName; } private string RequestJson; public void SetRequestJson(string requestJson)
{
RequestJson = requestJson;
} public string GetRequestJson() { return RequestJson; }
} /// <summary>
/// 返回的父级类型
/// </summary>
/// <typeparam name="T"></typeparam>
public class ResponseModel<T> : ResponseModel where T : new()
{ /// <summary>
/// 构造
/// </summary>
/// <param name="state">请求状态</param>
/// <param name="callback">透传字段</param>
/// <param name="postTime">请求时间</param>
/// <param name="msg">返回信息</param>
/// <param name="postContent">返回泛型</param>
public ResponseModel(RequestStateEnum state, string callback, string postTime, string msg, T postContent)
{
State = (int)state;
Callback = callback;
PostTime = postTime;
Msg = msg;
PostContent = postContent;
}
/// <summary>
/// 构造
/// </summary>
/// <param name="callback">透传字段</param>
/// <param name="postTime">请求时间</param>
/// <param name="msg">返回信息</param>
public ResponseModel(string callback, string postTime, string msg) : base(callback, postTime, msg)
{
//PostContent = new T();
}
/// <summary>
/// 构造
/// </summary>
/// <param name="callback">透传字段</param>
/// <param name="postTime">请求时间</param>
public ResponseModel(string callback, string postTime) : base(callback, postTime)
{ //PostContent = new T();
}
/// <summary>
/// 构造
/// </summary>
public ResponseModel()
{
PostContent = new T();
}
/// <summary>
/// 请求内容类以及返回内容类
/// </summary>
public T PostContent { get; set; } /// <summary>
/// 错误
/// </summary>
/// <param name="msg"></param>
/// <param name="state"></param>
/// <param name="obj"></param>
public void Fail(string msg, T obj, RequestStateEnum state = RequestStateEnum.Error)
{
PostContent = obj;
Msg = msg;
State = (int)state;
} /// <summary>
/// 成功
/// </summary>
/// <param name="obj"></param>
/// <param name="msg"></param>
/// <param name="state"></param>
public void Success(T obj, string msg = null, RequestStateEnum state = RequestStateEnum.Success)
{
Msg = msg;
this.PostContent = obj;
State = (int)state;
}
/// <summary>
/// 成功
/// </summary>
/// <param name="obj"></param>
public void Success(T obj)
{
this.PostContent = obj;
State = (int)RequestStateEnum.Success;
}
} }

4.html代码

<!doctype>
<head>
<script src="jquery-1.10.2.min.js"></script>
<!--<script src="jquery-1.11.1.js"></script>-->
<!--<script src="ajaxfileupload.js"></script>-->
<script>
$(document).ready(function () {
var appDomain = "http://localhost/TLSC.Api.File/";
$("#btn_fileUpload").click(function () {
/**
* 用ajax方式上传文件 -----------
* */
//-------asp.net webapi fileUpload
//
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: appDomain + 'File/Upload/ImgUpload',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (data) {
console.log(JSON.stringify(data));
}
});
//----end asp.net webapi fileUpload
//----.net core webapi fileUpload
// var fileUpload = $("#files").get(0);
// var files = fileUpload.files;
// var data = new FormData();
// for (var i = 0; i < files.length; i++) {
// data.append(files[i].name, files[i]);
// }
// $.ajax({
// type: "POST",
// url: appDomain+'api/Files',
// contentType: false,
// processData: false,
// data: data,
// success: function (data) {
// console.log(JSON.stringify(data));
// },
// error: function () {
// console.log(JSON.stringify(data));
// }
// });
//--------end net core webapi fileUpload
/**
* ajaxfileupload.js 方式上传文件
* */
// $.ajaxFileUpload({
// type: 'post',
// url: appDomain + 'api/Files',
// secureuri: false,
// fileElementId: 'files',
// success: function (data) {
// console.log(JSON.stringify(data));
// },
// error: function () {
// console.log(JSON.stringify(data));
// }
// });
});
//end click
})
</script>
</head>
<title></title>
<body>
<article>
<header>
<h2>article-form</h2>
</header>
<p>
<form action="/" method="post" id="uploadForm" enctype="multipart/form-data">
<input type="file" id="files" name="files" placeholder="file" multiple>file-multiple属性可以选择多项<br><br>
<input type="button" id="btn_fileUpload" value="fileUpload">
</form>
</p>
</article>
</body>

6.上传成功

1.5 WEB API 上传文件

demo就不贴了,拷贝上面的代码直接写就行了。