Home > Backend Development > C#.Net Tutorial > asp.net core mvc implementation of file upload example

asp.net core mvc implementation of file upload example

高洛峰
Release: 2017-02-07 11:33:03
Original
1197 people have browsed it

The file upload function is used at work. In this sharing~~

Controller:

public class PictureController : Controller
  {
    private IHostingEnvironment hostingEnv;
 
    public PictureController(IHostingEnvironment env)
    {
      this.hostingEnv = env;
    }
    // GET: /<controller>/
    public IActionResult Index()
    {
      return View();
    }
    public IActionResult UploadFiles()
    {
      return View();
    }
    [HttpPost]
    public IActionResult UploadFiles(IList<IFormFile> files)
    {
      long size = 0;
      foreach (var file in files)
      {
        var filename = ContentDispositionHeaderValue
                .Parse(file.ContentDisposition)
                .FileName
                .Trim(&#39;"&#39;);
        //这个hostingEnv.WebRootPath就是要存的地址可以改下
        filename = hostingEnv.WebRootPath + $@"\{filename}";
        size += file.Length;
        using (FileStream fs = System.IO.File.Create(filename))
        {
          file.CopyTo(fs);
          fs.Flush();
        }
      }
      ViewBag.Message = $"{files.Count} file(s) /{ size}bytes uploaded successfully!";
       return View();
    }
 
  }
Copy after login

view:

<form asp-action="UploadFiles"
         asp-controller="Picture"
         method="post"
         enctype="multipart/form-data">
        <input type="file" name="files" multiple />
        <input type="submit" value="Upload Selected Files" />
 </form>
Copy after login

The file is uploaded to the wwwroot directory file , I don’t quite understand this and I’m still learning. Everyone is welcome to communicate~~

-------------------------- -------------------------------------------------- --------------------------

The following is the

post method for jquery ajax upload The z parameter of the action is useless because there is only one post method that will cause a 404 error, so I added another get action

Controller:

public IActionResult UploadFilesAjax()
{
  return View();
}
[HttpPost]
public IActionResult UploadFilesAjax(string z) 
{
  long size = 0;
  var files = Request.Form.Files;
  foreach (var file in files)
  {
    var filename = ContentDispositionHeaderValue
            .Parse(file.ContentDisposition)
            .FileName
            .Trim(&#39;"&#39;);
    filename = @"C:\Users\lg.HL\Desktop" + $@"\{filename}";    
    size += file.Length;
    using (FileStream fs = System.IO.File.Create(filename))
    {
      file.CopyTo(fs);
      fs.Flush();
    }
  }
  string message = $"{files.Count} file(s) / { size}bytes uploaded successfully!";
    return Json(message);
}
Copy after login

view

<form method="post" enctype="multipart/form-data">
      <input type="file" id="files"
          name="files" multiple />
      <input type="button"
          id="upload"
          value="Upload Selected Files" />
 </form>
Copy after login

jquery

<script type="text/javascript">
    $(document).ready(function () {
      $("#upload").click(function (evt) {
        var fileUpload = $("#files").get(0);
        var files = fileUpload.files;
        var data = new FormData();
        for (var i = 0; i < files.length ; i++) {
          data.append(files[i].name, files[i]);
        }
        $.ajax({
          type: "POST",
          url: "/Picture/UploadFilesAjax",
          contentType: false,
          processData: false,
          data: data,
          success: function (message) {
            alert(message);
          },
          error: function () {
            alert("There was error uploading files!");
          }
        });
      });
    });
</script>
Copy after login


## Welcome everyone to communicate ~ The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to asp.net core mvc implementation of file upload examples, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template