1.
<input type="file" id="files" name="files" multiple />
<input type="button" id="upload" value="Upload Selected Files" />
$("#upload").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
console.log("length=" + files.length);
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
data.append("1111", "222");
$.ajax({
type: "POST",
url: "http://localhost:50090/api/test",
contentType:false,
dateType:"json",
processData: false,
data: data,
success: function (json) {
alert(json);
var list = JSON.parse(json);
alert(list.res);
},
error: function () {
alert("There was error uploading files!");
}
});
});
后台
[HttpPost]
public ActionResult UploadFile( )
{
string path = "";
long size = 0;
int i = 0;
var files = HttpContext.Request.Form.Files;
if (files.Count > 0)
{
//可以写遍历files
var file = files[0];
#region 图片文件的条件判断
文件后缀
//string fileExtension = Path.GetExtension(file.FileName);
判断后缀是否是图片
//const string fileFilt = ".gif|.jpg|.jpeg|.png";
//if (fileExtension == null)
//{
// break;
// //return Error("上传的文件没有后缀");
//}
//if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
//{
// break;
// //return Error("请上传jpg、png、gif格式的图片");
//}
判断文件大小
//long length = file.InputStream.Length;
//if (length > 1024 * 1024 * 2) //2M
//{
// break;
// //return Error("上传的文件不能大于2M");
//}
#endregion
string upload_path = Directory.GetCurrentDirectory() + "/wwwroot";
DateTime now = DateTime.Now;
if (Directory.Exists(upload_path + "/images/" + now.Year) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(upload_path + "/images/" + now.Year);
}
if (Directory.Exists(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd")) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd"));
}
upload_path = upload_path + "/images/" + now.Year + "/" + now.ToString("MMdd");//新的目录
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
string houzhui = filename.Substring(filename.IndexOf("."));
var filenamenew = DateTime.Now.ToString("yyyyMMddHHmmssfff") + houzhui;
filename = upload_path+"/" + filenamenew;
path= "/images/" + now.Year + "/" + now.ToString("MMdd")+"/"+ filenamenew;
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
i += 1;
}
}
}
2
前段
@{
ViewData["Title"] = "Home Page";
}
<form id="form1" action="~/Home/UploadFiles" enctype="multipart/form-data" method="post">
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<input type="file" name="files" multiple />//最后一个属性是多张上传
<input type="submit" value="上传"/>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
</form>
控制器
[HttpPost]
public IActionResult UploadFiles(IList<IFormFile> files)
{
long size = 0;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = @"D:\111111" + $@"\{filename}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
return View("Index");
}
这里有几个重点:
1:引用 IFormCollection 类 获取 Asp.Net.Core 中 Http 请求的一个类,就可以直接获取form表单中的参数,
应为 ASP.NET Core 中,没有了 IIS ,它的 HttpContext 只能用 IFormCollection 生成获取form表单中的数据
命名空间为 :namespace Microsoft.AspNetCore.Http
2: 引用 IFormFileCollection 类 获取上传图片的文件名
命名空间为 :namespace Microsoft.AspNetCore.Http
IFormFile GetFile(string name);,获取一张图片的名称
IReadOnlyList<IFormFile> GetFiles(string name);获取多张图片的名称
3:创建一个 Hashtable hash = new Hashtable(); 类 保存图片路劲进行返回数据
总结:
asp.net mvc 与 asp.net core 中上传图片区别点是
net core没有httpContext 不能采用这种方式获取 http请求中的form 数据,只能使用 IFormCollection 接口类
多熟悉操作IO流自能而能就可以轻松搞定上传图片
[HttpPost]
public ActionResult Upload(IFormCollection Files )
{
try
{
//var form = Request.Form;//直接从表单里面获取文件名不需要参数
string dd = Files["File"];
var form = Files;//定义接收类型的参数
Hashtable hash = new Hashtable();
IFormFileCollection cols = Request.Form.Files;
if (cols == null || cols.Count == 0)
{
return Json(new { status = -1, message = "没有上传文件", data = hash });
}
foreach (IFormFile file in cols)
{
//定义图片数组后缀格式
string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
//获取图片后缀是否存在数组中
string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
if (LimitPictureType.Contains(currentPictureExtension))
{
//为了查看图片就不在重新生成文件名称了
// var new_path = DateTime.Now.ToString("yyyyMMdd")+ file.FileName;
var new_path = Path.Combine("uploads/images/", file.FileName);
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", new_path);
using (var stream = new FileStream(path, FileMode.Create))
{
//图片路径保存到数据库里面去
//bool flage = QcnApplyDetm.FinancialCreditQcnApplyDetmAdd(EntId, CrtUser, new_path);
//if (flage == true)
//{
//再把文件保存的文件夹中
file.CopyTo(stream);
hash.Add("file", "/" + new_path);
//}
}
}
else
{
return Json(new { status = -2, message = "请上传指定格式的图片", data = hash });
}
}
return Json(new { status = 0, message = "上传成功", data = hash });
}
catch (Exception ex)
{
return Json(new { status = -3, message = "上传失败", data = ex.Message });
}
}