就目前来说,ASP.NET Core2.1了,已经相当成熟了,希望下个项目争取使用吧!!

上传文件的三种方式("我会的,说不定还有其他方式")

模型绑定

Ajax

WebUploader

  官方机器翻译的地址:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads,吐槽一下,这翻译的啥玩腻啊。。。

<form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave">
        <div>
            <div>
                <p>Form表单多个上传文件:</p>
                <input type="file" name="files" multiple />
                <input type="submit" value="上传" />
            </div>
        </div>
    </form>

  其中,asp-controller和asp-action,(这个是TagHelper的玩法)是我们要访问的控制器和方法,不懂taghelper的可以看一下我关于aspnetcore的taghelper的相关文章zara说taghelper

  给我们的input标签加上 multiple 属性,来支持多文件上传.

创建一个控制器,我们编写上传方法如下:

public async Task<IActionResult> FileSave(List<IFormFile> files)

        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            string webRootPath = _hostingEnvironment.WebRootPath;

            string contentRootPath = _hostingEnvironment.ContentRootPath;

            foreach (var formFile in files)

            {

                if (formFile.Length > 0)

                {
                    string fileExt = GetFileExt(formFile.FileName); //文件扩展名,不含“.”

                    long fileSize = formFile.Length; //获得文件大小,以字节为单位

                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名

                    var filePath = webRootPath +"/upload/" + newFileName;

                    using (var stream = new FileStream(filePath, FileMode.Create))

                    {

                        await formFile.CopyToAsync(stream);

                    }

                }

            }
            return Ok(new { count = files.Count, size });

        }
View Code

相关文章:

  • 2021-09-27
  • 2021-11-11
  • 2021-11-20
  • 2021-09-26
  • 2021-11-30
  • 2021-11-20
猜你喜欢
  • 2021-12-28
  • 2021-12-10
  • 2022-12-23
  • 2021-11-20
  • 2021-10-04
  • 2021-09-19
  • 2021-08-15
相关资源
相似解决方案