文件上传功能在实际开发中经常使用,在 .Net Core中,文件上传接收类型不再使用 HttpPostedFile 或 HttpFileCollection来接收,而是使用 IFormFile 或 IFormFileCollection来接收。
下面看一个例子就明白怎么使用了,具体代码如下:
<form enctype="multipart/form-data" asp-controller="home" asp-action="upload" method="post" class="form-horizontal">
<div class="form-group">
<label for="input" class="col-sm-2 control-label">头像</label>
<div class="col-sm-5">
<input type="file" name="input" id="input" class="custom-file-input"/>
<label class="custom-file-label"></label>
</div>
<input type="submit" value="提交" />
</div>
</form>
@section scripts{ <script> $(document).ready(function () { $(".custom-file-input").on("change", function () { var fileName = $(this).val().split("\").pop(); $(this).next(".custom-file-label").html(fileName); }) }); </script> }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using FileUpload.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Hosting; using System.IO; namespace FileUpload.Controllers { public class HomeController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public HomeController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public IActionResult Index() { return View(); } [HttpPost] public IActionResult Upload(IFormFile input) { if (input == null) return BadRequest(); string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images"); string uniqueFileName = Guid.NewGuid().ToString() + "_" + input.FileName; string filePath = Path.Combine(uploadsFolder,uniqueFileName);
using(FileStream fileStream = new FileStream(filePath,FileMode.Create)
{
input.CopyTo(fileStream);
} return Ok(); } } }
多文件上传
<form enctype="multipart/form-data" asp-controller="home" asp-action="upload" method="post" class="form-horizontal">
<div class="form-group">
<label for="input" class="col-sm-2 control-label">头像</label>
<div class="col-sm-5">
<input type="file" name="input" id="input" class="custom-file-input" multiple />
<label class="custom-file-label"></label>
</div>
<input type="submit" value="提交" />
</div>
</form>
@section scripts{ <script> $(document).ready(function () { $(".custom-file-input").on("change", function () { var fileLabel = $(this).next(".coustom-file-lable"); var files = $(this)[0].files; if (files.length > 1) { fileLabel.html("你已选择了" + files.length + "个文件"); } else { fileLabel.html(files[0].name); } }) }); </script> }
[HttpPost] public IActionResult Upload(IFormFileCollection input) { if (input == null) return BadRequest(); string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images"); string uniqueFileName = Guid.NewGuid().ToString() + "_" + input[0].FileName; string filePath = Path.Combine(uploadsFolder,uniqueFileName);
using(FileStream fileStream = new FileStream(filePath,FileMode.Create)
{
input[0].CopyTo(fileStream);
}
return Ok();
}