• 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异常处理整理

  • 相关阅读:
    selenium使用
    爬取梨视频
    django实现事务
    django admin模块使用
    跨域问题和django中实现跨域
    Java多线程Condition定点通知
    Java创建线程四种方式
    JVM之JVM体系结构
    Java线程状态
    Java正则表达式解析网页源码
  • 原文地址:https://www.cnblogs.com/tianma3798/p/7391424.html
Copyright © 2020-2023  润新知