码迷,mamicode.com
首页 > Web开发 > 详细

.net core多文件上传 日志记录

时间:2020-07-28 22:47:04      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:thread   exists   lin   一个   logging   result   style   修改   tip   

光文件上传只生成页面就行了,在这里我只是做个文件上传的测试,至于.net core的依赖注入和一些其他的配置信息,等我整理好了再来谈一谈,最近一直在整文件上传

大部分的步骤和我上一篇文件一样,只在后台做了一些修改

上篇文章地址:https://www.cnblogs.com/ataoliu/p/13387464.html

控制器里面的代码

using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using CoreUpLoad.Models;
using Microsoft.AspNetCore.Http;
using System.IO;

namespace CoreUpLoad.Controllers
{
    public class HomeController : Controller
    {

        public IActionResult Upload()
        {
            return View();
        }

        #region MyRegion


        [HttpPost]    //上传文件是 post 方式,这里加不加都可以
        public async Task<IActionResult> UploadFiles(List<IFormFile> files)
        {
           
            var filepath = Directory.GetCurrentDirectory() + "\\file";  //存储文件的路径


            foreach (var item in files)     //上传选定的文件列表
            {
                if (item.Length > 0)        //文件大小 0 才上传
                {
                    var thispath = filepath + "\\" + item.FileName;     //当前上传文件应存放的位置

                    if (System.IO.File.Exists(thispath) != true)        //如果文件已经存在,跳过此文件的上传
                    {
                        //上传文件
                        using (var stream = new FileStream(thispath, FileMode.Create))      //创建特定名称的文件流
                        {
                            try
                            {
                                await item.CopyToAsync(stream);     //上传文件
                            }
                            catch (Exception)
                            {
                            }

                        }
                    }
                }
            }
            return View();
        }
    }
}

控制器方法

UploadFiles(List<IFormFile> files)
UploadFiles是上传用的方法
List<IformFile>是参数,因为是多文件上传,所以要使用一个集合去接受上传的文件
接收到文件后自己在根据需求去写一些逻辑代码

前台页面的写法

@{
    ViewData["Title"] = "Upload";
}

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFiles">
    <div class="form-group">
        <div class="col-md-12">
            <p>选择要上传的文件</p>
            <input type="file" name="files" multiple />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-12">
            <input type="submit" value="上传" />
        </div>
    </div>
</form>
multiple 一定要写,因为他是html支持多文件上传的一个属性
同时form表单enctype="multipart/form-data"属性也要加上,不然后台接收不到文件的

.net core多文件上传 日志记录

标签:thread   exists   lin   一个   logging   result   style   修改   tip   

原文地址:https://www.cnblogs.com/ataoliu/p/13393835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!