ASP.NET Core 文件上传

进行保存操作的控制器代码

public class UploadFilesController : ControllerBase
    {
        public IActionResult Index()
        {
            return Ok();
        }

        [HttpPost("UploadFiles")]
        public async Task<IActionResult> Post(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);

            // 临时文件的路径
            var filePath = Path.GetTempFileName();
           
            foreach (var formFile in files)
            {
                //取后缀名
                var fileN = formFile.FileName.ToString();
                var fileLastName = fileN.Substring(fileN.LastIndexOf(".") + 1,
                    (fileN.Length - fileN.LastIndexOf(".") - 1));

                filePath = @"Upload\"+"one."+fileLastName;//保存文件的路径
                if (formFile.Length > 0)
                {
                    //根据路径创建文件
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }
            // process uploaded files
            // Don't rely on or trust the FileName property without validation.
            return Ok(new { count = files.Count, size, filePath });
        }

    }
View Code

视图代码

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <div class="row">
            <form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Index">
                <div class="form-group">
                    <div class="col-md-10">
                        <p>Upload one or more files using this form:</p>
                        <input type="file" name="files" multiple>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-10">
                        <input type="submit" value="Upload">
                    </div>
                </div>
            </form>
        </div>
    </div>
View Code

来自于官网Demo https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2

posted @ 2019-05-14 09:50  Uyd  阅读(1039)  评论(0编辑  收藏  举报