赞
踩
文件上传功能在实际开发中经常使用,在 .Net Core中,文件上传接收类型不再使用 HttpPostedFile 或 HttpFileCollection来接收,而是使用 IFormFile 或 IFormFileCollection来接收。
下面看一个例子就明白怎么使用了,具体代码如下:
- <div class="form-group">
- <form enctype="multipart/form-data" asp-controller="home" asp-action="upload" method="post">
- <input type="file" name="input" id="input" class="custom-file-input" />
- <label class="custom-file-label" for="input"></label>
- <input type="submit" value="提交" />
- </form>
- </div>
-
-
- @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);
-
- input.CopyTo(new FileStream(filePath, FileMode.Create));
-
-
- return Ok();
- }
- }
- }
多文件上传
- <div class="form-group">
- <form enctype="multipart/form-data" asp-controller="home" asp-action="upload" method="post">
- <input type="file" name="input" id="input" class="custom-file-input" multiple />
- <label class="custom-file-label" for="input"></label>
- <input type="submit" value="提交" />
- </form>
- </div>
-
-
- @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);
-
- input[0].CopyTo(new FileStream(filePath, FileMode.Create));
-
-
- return Ok();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。