1、目的需求:前台批量上传文件,并在后台进行接收
前台代码:配置URL路径: url: '/KeepElectricty/uploadfiles'其中KeepElectricty是控制器,uploadfiles是接收方法
<!--HTML部分-->
<div class="layui-upload" style="margin:10px;margin-left: 30px;">
<button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
<div class="layui-upload-list">
<table class="layui-table" id="fileTable">
<thead>
<tr>
<th>文件名</th>
<th>大小</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody id="demoList"></tbody>
</table>
</div>
<button type="button" class="layui-btn" id="testListAction">开始上传</button>
</div>
<script>
init();
function init() {
$("#testListAction").hide();
$("#fileTable").hide();
layui.use('upload', function () {
var $ = layui.jquery
, upload = layui.upload;
//多文件列表示例
var demoListView = $('#demoList')
, uploadListIns = upload.render({
elem: '#testList'
, url: '/KeepElectricty/UploadFiles'
, accept: 'file'
, multiple: true
, auto: false
, bindAction: '#testListAction'
, choose: function (obj) {
$("#testListAction").show();
$("#fileTable").show();
var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
//读取本地文件
obj.preview(function (index, file, result) {
var tr = $(['<tr id="upload-' + index + '">'
, '<td>' + file.name + '</td>'
, '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
, '<td>等待上传</td>'
, '<td>'
, '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
, '</td>'
, '</tr>'].join(''));
//单个重传
tr.find('.demo-reload').on('click', function () {
obj.upload(index, file);
});
//删除
tr.find('.demo-delete').on('click', function () {
delete files[index]; //删除对应的文件
tr.remove();
uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
});
demoListView.append(tr);
});
}
, done: function (res, index, upload) {
if (res.code == 0) { //上传成功
var tr = demoListView.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
tds.eq(3).html(''); //清空操作
return delete this.files[index]; //删除文件队列已经上传成功的文件
} else if (res.code == 1) {
this.error(index, upload);
} else if (res.code == 5) {
layui.use('layer', function () {
layer = layui.layer;
layer.msg('上传时发生致命错误!', {
icon: 2
});
});
}
}
, error: function (index, upload) {
var tr = demoListView.find('tr#upload-' + index)
, tds = tr.children();
tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
}
});
});
}
</script>
后台接收代码:
public ActionResult UploadFiles()
{
string path = "~/UploadFiles/";
try
{
var file = Request.Files[0]; //获取选中文件
var filecombin = file.FileName.Split('.');
if ( file == null || String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0 || filecombin.Length < 2)
{
return Json(new { msg = "上传出错", code = 1 });
}
//项目相对路径
string local = path.Replace("~/", "").Replace('/', '\\');
//物理路径
string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, local);
//文件名称
var saveName = file.FileName;
//扩展名
var extension = filecombin[filecombin.Length - 1];
//新名称(GUID格式)
var uName = Guid.NewGuid().ToString("N");
//判断文件存放路径是否存在
if (!System.IO.Directory.Exists(localPath))
{
System.IO.Directory.CreateDirectory(localPath);
}
//文件保存路径
string localURL = Path.Combine(local, uName + "." + extension);
//保存文件
file.SaveAs(Path.Combine(localPath, uName + "." + extension));
return Json(new { msg = "上传成功", code = 0 });
}
catch (Exception e)
{
return Json(new { msg = "上传异常" + e.Message, code = 1 });
}
}
以下是调试:
A:选择文件
B:点击上传
C:进行DEBUG调试
此时通过监视发现文件已经上传过来。
D:验证文件夹下是否已经存储
如果使用WEBAPI请使用以下方法接收
//接收文件
HttpFileCollection files = HttpContext.Current.Request.Files;
foreach (string key in files.AllKeys)
{
HttpPostedFile file = files[key];
if (string.IsNullOrEmpty(file.FileName) == false)
{
filepath = HttpContext.Current.Server.MapPath("~/UploadFiles/") + file.FileName;
file.SaveAs(filepath);
}
}