将内容复制到流时出错. IFormFile read Asp.Net

t5zmwmid  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(270)

我正在尝试从xsls读取数据以更新数据库。注意:这段代码在我的本地机器上运行良好。2只有当我发布到服务器时才会出现错误。
下面是错误

{error: "Error while copying content to a stream.",…}
error
: 
"Error while copying content to a stream."
exceptionType
: 
"System.Net.Http.HttpRequestException"
innerException
: 
"Cannot access a disposed object.\r\nObject name: 'System.Net.Http.StreamContent'."
stackTrace
: 
"   at System.Net.Http.HttpContent.CheckDisposed()\r\n

这是我代码块

[RequestFormLimits(MultipartBodyLengthLimit = 52428800, ValueLengthLimit = 52428800)]
        public async Task<IActionResult> ImportSheet([FromForm] IFormFile uploadedFile)
        {
            var isClean = await _antimalwareScanService.PostSingleFileResponseAsync(uploadedFile);
            if (isClean)
            {
      
                if ( uploadedFile is null)
                {
                    return BadRequest();
                }
                if (!string.IsNullOrEmpty(uploadedFile.FileName))
                {
                    using var stream = uploadedFile.OpenReadStream();
                    //using var memoryStream = new MemoryStream();
                    //await stream.CopyToAsync(memoryStream);
                     using  ExcelPackage excel = new(stream);
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                    ExcelWorkbook workbook = excel.Workbook;

                    ExcelWorksheets worksheets = workbook.Worksheets;
                    var psWorksheets = worksheets.FirstOrDefault(x =>    x.Name.ToLower().Contains("prof services"));
                    if (psWorksheets != null)
                    {
                         await _fileViewModelService.UploadProfServicesFile(psWorksheets);
                    }
                    stream.Dispose();
                }
            }

            return Ok();
        }
    }
cbeh67ev

cbeh67ev1#

你可以删除[FromForm],因为.net核心知道从哪里获取数据。2我还详细介绍了如何将其作为stream,然后作为byteArray,最后作为Base64。3你可以使用任何适合你的方法。

[HttpPost("File")]
    public async Task<IActionResult> ImportSheet(IFormFile uploadedFile)
    {
        if (uploadedFile.Length > 0)
        {
            using (var ms = new MemoryStream())
            {
                await uploadedFile.CopyToAsync(ms);
                var fileBytes = ms.ToArray();
                string s = Convert.ToBase64String(fileBytes);
            }
        }
        return Ok();
    }

相关问题