.Net Core多文件上传
weixin_43189545 人气:0这段时间刚刚接触了.NET Core,工作要求,从0开始,给用户开发了一个小型的内部系统。用户提出需求,要求能实现多文件上传,上传不同位置的文件,可以删除。
找来找去还是layui的文件上传符合审美,不多废话上代码
1.前端页面
<div class="layui-upload"> <button type="button" class="layui-btn layui-btn-normal" id="testList">Search</button> <div class="layui-upload-list"> <table class="layui-table"> <thead> <tr> <th>File Name</th> <th>Size</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody id="demoList"></tbody> </table> </div> <button type="button" class="layui-btn" id="testListAction" onclick="noFile()">Upload</button> </div>
script部分
<script> layui.use('upload', function () { var upload = layui.upload; var demoListView = $('#demoList') , uploadListIns = upload.render({ elem: '#testList' , url: '你的文件上传接口' , accept: 'file' , multiple: true , size: 30000 , auto: false , bindAction: '#testListAction' , choose: function (obj) { var files = this.file = obj.pushFile(); //将每次选择的文件追加到文件队列 console.log(uploadListIns); //读取本地文件 obj.preview(function (index, file, result) { var tr = $(['<tr id="upload-' + index + '">' , '<td>' + file.name + '</td>' , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>' , '<td>Wait to upload</td>' , '<td>' , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>' , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">Delete</button>' , '</td>' , '</tr>'].join('')); //删除 tr.find('.demo-delete').on('click', function () { delete files[index]; //删除对应的文件 tr.remove(); uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选 //console.log(files); }); 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;">Success</span>'); tds.eq(3).html(''); //清空操作 return delete this.files[index]; //删除文件队列已经上传成功的文件 } , error: function (index, upload) { } }); }) </script>
到这里的话其实就是从官网copy下来的哈哈哈,接下来的就是重点啦
2.后端部分
这里是controller部分
public async Task<IActionResult> UploadFiles(List<IFormFile> file) { EditorDataResult editorResult = new EditorDataResult(); foreach (var formFile in file) { if (formFile.Length > 0) { FileInfo fi = new FileInfo(formFile.FileName); string ext = fi.Extension; var orgFileName = fi.Name; var newFileName = Guid.NewGuid() + ext; var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "你想要上传到文件夹"); var filePath = Path.Combine(uploads, newFileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await formFile.CopyToAsync(stream); } editorResult.code = 0; } else { editorResult.code = 1; } } JavaScriptSerializer jss = new JavaScriptSerializer(); string data = jss.Serialize(editorResult);//转换为Json格式! return Json(data); }
model部分 主要就是回调json数据给layui
namespace LayuiMvc.Common.Result { public class EditorDataResult { public int code { get; set; } public string msg { get; set; } public Dictionary<string, string> data { get; set; } } }
到这边基本上文件上传已经done了
上图
加载全部内容