Asp.Net Core 文件上传处理

本文主要介绍后台接收处理

1.在使用控制器接收

   1: [HttpPost]
   2: public IActionResult UploadFiles(IList<IFormFile> files)
   3: {
   4:     long size = 0;
   5:     foreach(var file in files)
   6:     {
   7:         var filename = ContentDispositionHeaderValue
   8:                         .Parse(file.ContentDisposition)
   9:                         .FileName
  10:                         .Trim('"');
  11:         filename = hostingEnv.WebRootPath + $@"\{fileName}";
  12:         size += file.Length;
  13:         using (FileStream fs = System.IO.File.Create(filename))
  14:         {
  15:            file.CopyTo(fs);
  16:            fs.Flush();
  17:         }
  18:     }

2.使用HttpRequest接收

方式1:

   1: [HttpPost]
   2: public IActionResult UploadFilesAjax()
   3: {
   4:     long size = 0;
   5:     var files = Request.Form.Files;
   6:     foreach (var file in files)
   7:     {
   8:         var filename = ContentDispositionHeaderValue
   9:                         .Parse(file.ContentDisposition)
  10:                         .FileName
  11:                         .Trim('"');
  12:         filename = hostingEnv.WebRootPath + $@"\{filename}";
  13:         size += file.Length;
  14:         using (FileStream fs = System.IO.File.Create(filename))
  15:         {
  16:            file.CopyTo(fs);
  17:            fs.Flush();
  18:         }
  19:     }
  20:     string message = $"{files.Count} file(s) / 
  21:                        {size} bytes uploaded successfully!";
  22:     return Json(message);
  23: }

方式2:

    //接收文件
    var files = req.Form.Files;
    if (files.Count <= 0)
        throw new Exception("获取上传文件失败");
    IFormFile _file = files[0];
    string backInfo = req.Form["backinfo"];
    if (string.IsNullOrEmpty(backInfo))
        throw new Exception("获取文件信息失败");
    UploadMsg upMsg = backInfo.JsonDeserializer<UploadMsg>();
    this.file = new UploadInfo(upMsg);
    //获取文件数据
    Stream stream = _file.OpenReadStream();
    try
    {
        byte[] dataOne = new byte[stream.Length];
        stream.Read(dataOne, 0, dataOne.Length);
        AppendFile(dataOne);
    }
    finally
    {
        stream.Close();
    }

支持.Net Core的上传控件:https://github.com/tianma3798/Uploader

更多:

Asp.Net Core获取当前上线文对象

Asp.Net Core 视图整理(一)

Asp.Net Core异常处理整理

posted @ 2017-08-18 19:18  天马3798  阅读(3170)  评论(3编辑  收藏  举报