最近研究了一下如何利用asp.net mvc实现文件上传操作,经过一番摸索,现在将代码贴出来。本次功能只有单纯实现文件上传,不包括对上传的文件进行读操作,或者返回到前端页面显示的功能
前端代码
<input type="file" id="btn_file" style="display:none"><!--隐藏起来-->
如果需要显示上传按钮的,可以去掉样式style
js代码部分
layui.use(['table', 'laydate', 'layer', 'form', 'tree', 'util', 'upload'], function () {
let upload = layui.upload;
//执行文件上传,任何文件格式都可以
var uploadInst = upload.render({
elem: '#btn_file' //绑定元素
, url: 'upload/' //上传接口
//, progress: function (n, elem, res, index) {
// var percent = n + '%' //获取进度百分比
// element.progress('demo', percent); //可配合 layui 进度条元素使用
// console.log(elem); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。
// console.log(res); //得到 progress 响应信息
// console.log(index); //得到当前上传文件的索引,多文件上传时的进度条控制,如:
// element.progress('demo-' + index, n + '%'); //进度条
//}
, before: function (obj) {
var l = layer.msg('导入中,请稍候', { icon: 16, time: false, shade: 0.8 });
}
, done: function (res) {
//上传完毕回调
if (res != null) {
layer.msg('导入成功', { icon: 1 });
}
}
, error: function () {
//请求异常回调
}
});
后端C#代码
//文件上传
[HttpPost]
public List<string> upload()
{
HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
string url = System.Web.HttpContext.Current.Server.MapPath("~/Upload");
List<string> result = new List<string>();//result的目的就是将上传好的文件路径传到前端,方便前端页面显示该图片
HttpFileCollection filelist = System.Web.HttpContext.Current.Request.Files;
if (filelist != null && filelist.Count > 0)
{
for (int i = 0; i < filelist.Count; i++)
{
HttpPostedFile file = filelist[i];
String Tpath = DateTime.Now.ToString("yyyy-MM-dd");
string filename = file.FileName;
string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string FilePath = url + "/" + Tpath + "/";
string aFirstName = Path.GetExtension(filename);
DirectoryInfo di = new DirectoryInfo(FilePath);
if (!di.Exists) { di.Create(); }
try
{
string fileUrl = FilePath + FileName + aFirstName;
file.SaveAs(fileUrl);//保存文件到项目所在磁盘
result.Add("/Upload/" + Tpath + "/" + FileName + aFirstName);
}
catch (Exception ex)
{
result.Add("上传文件写入失败:" + ex.Message);
}
}
}
else
{
result.Add("上传的文件信息不存在!");
}
return result;
}
引用部分
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using System.IO;