asp.net core mvc如何实现文件上传的教程

作者:袖梨 2022-06-25

工作用到文件上传的功能,在这个分享下 ~~

Controller:   

 代码如下 复制代码
publicclassPictureController : Controller
  {
    privateIHostingEnvironment hostingEnv;
 
    publicPictureController(IHostingEnvironment env)
    {
      this.hostingEnv = env;
    }
    // GET: //
    publicIActionResult Index()
    {
      returnView();
    }
    publicIActionResult UploadFiles()
    {
      returnView();
    }
    [HttpPost]
    publicIActionResult UploadFiles(IList files)
    {
      longsize = 0;
      foreach(var fileinfiles)
      {
        var filename = ContentDispositionHeaderValue
                .Parse(file.ContentDisposition)
                .FileName
                .Trim('"');
        //这个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!";
       returnView();
    }
 
  }
 

view:

 
 代码如下 复制代码
         asp-controller="Picture"
         method="post"
         enctype="multipart/form-data">
        
        
 
 

文件是上传到wwwroot目录文件下的,这我也看不太懂还在学习,欢迎大家交流~~

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

下面是jquery ajax方式上传的

post方式的action的z参数没用 因为只有一个post方式的会404错误所以又加了一个get的action

Controller:

 
 代码如下 复制代码
public IActionResult UploadFilesAjax()
{
  returnView();
}
[HttpPost]
public IActionResult UploadFilesAjax(string z)
{
  long size = 0;
  varfiles = Request.Form.Files;
  foreach (varfileinfiles)
  {
    varfilename = ContentDispositionHeaderValue
            .Parse(file.ContentDisposition)
            .FileName
            .Trim('"');
    filename = @"C:Userslg.HLDesktop" + $@"{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!";
    returnJson(message);
}
 

view

 
 代码如下 复制代码
      
          name="files"multiple />
      
          id="upload"
          value="Upload Selected Files"/>
 
 

jquery

 
 代码如下 复制代码
 

相关文章

精彩推荐