关于.net:如何在-ASPNet-Core-MVC-中实现文件上传

5次阅读

共计 2739 个字符,预计需要花费 7 分钟才能阅读完成。

ASP.Net Core MVC 实现了将 上传文件 间接映射到 model 中,只有这个 model 实现了 IFormFile 接口即可,回忆一下,model binding 的作用就是将 Request 映射到 Action 办法参数的过程,这样就简化了原来须要间接对 Request 的拜访,同时也不便后续做单元测试,本篇中的 IFormFile 接口就简化了对 Request 中的 file 拜访。

上传一个文件

在这一节中咱们将会演示如何通过 IFromFile 接口来对接 client 上传一个或者多个文件,先看一下 IFromFile 接口的定义。


public interface IFormFile
{string ContentType { get;}
    string ContentDisposition {get;}
    IHeaderDictionary Headers {get;}
    long Length {get;}
    string Name {get;}
    string FileName {get;}
    Stream OpenReadStream();
    void CopyTo(Stream target);
    Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}

而后咱们创立一个 FileUploadController 类,构建一个 UploadFile 办法来接管 client 上传的文件。


    public class FileUploadController : Controller
    {[HttpPost("UploadFile")]
        public async Task<IActionResult> UploadFile(IFormFile iFormFile)
        {if (iFormFile == null || iFormFile.Length == 0)
                return Content("No file selected for upload.");

            var filePath = Path.GetTempFileName();

            using (var stream = new FileStream(filePath, FileMode.Create))
            {await iFormFile.CopyToAsync(stream);
            }

            return RedirectToAction("Home");
        }
    }

从下面代码能够看到,UploadFile 办法中应用了 IFormFile 实例作用参数,如果 iFormFile 里无数据或者空援用就返回 No file selected for upload. 反之就保留文件并跳转到 Home 页。

如果有多文件上传需要,能够将 IFromFile 改成数组模式,如下代码所示:


        [HttpPost("UploadFiles")]
        public async Task<IActionResult> UploadFiles(List<IFormFile> iFormFiles)
        {var filePath = Path.GetTempFileName();

            foreach (var iFormFile in iFormFiles)
            {if (iFormFile.Length > 0)
                {using (var stream = new FileStream(filePath, FileMode.Create))
                    {await iFormFile.CopyToAsync(stream);
                    }
                }
            }
            return RedirectToAction("Home");
        }

下面代码用了 GetTempFileName() 来获取临时文件,这里有一个坑须要留神,如果这个门路下的临时文件超过 65535 的话将会抛出异样,解决办法就是:

  • 在解决完之后删除临时文件。
  • 将文件保留在你指定的中央。

下载 file

要想从 ASP.Net Core MVC 中下载文件,思考如下代码:


        public async Task<IActionResult> DownloadFile(string path, string filename)
        {if (filename == null || filename.Length == 0)
                return Content("No file selected for download.");

            var filePath = Path.Combine(path, filename);
            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(filePath, FileMode.Open))
            {await stream.CopyToAsync(memoryStream);
            }

            memoryStream.Position = 0;

            return File(memoryStream, "text/plain", Path.GetFileName(path));
        }

在 DownloadFile 办法中应用了 CopyToAsync 办法将文件 copy 到 MemoryStream 中,而后通过返回 FileStreamResult 将文件流返回给客户端。

创立一个 Razor View

接下来创立一个 Razor View 用来做文件上传的界面,在 View 界面中增加如下代码:


@{ViewData["Title"] = "Home Page";
}

<div class="text-center">

    <form asp-controller="FileUpload" asp-action="UploadFile" method="post"
          enctype="multipart/form-data">
        <input type="file" name="iFormFile" />
        <button type="submit">Upload File</button>
    </form>
    <form asp-controller="FileUpload" asp-action="UploadFiles" method="post"
          enctype="multipart/form-data">
        <input type="file" name="iFormFiles" multiple />
        <button type="submit">Upload Files</button>
    </form>

</div>

接下来能够把程序跑起来,上传一个文件,截图如下:

通过本篇文章能够看出 ASP.Net Core MVC 中的 model binding 真的是太强大了,你能够上传一个或者多个 size 不定的文件,对于更多 ASP.Net Core 中上传下载的细节,我会放到前面的文章和大家细聊。

译文链接:https://www.infoworld.com/art…

更多高质量干货:参见我的 GitHub: csharptranslate

正文完
 0