Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

ajax - Request.Files in ASP.NET CORE

I am trying to upload files using aspnet core using ajax request . In previous versions of .net i used to handle this using

 foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];
                //Save file content goes here

                fName = file.FileName;
     (...)

but now its showing error at request.files how can i get it to work ? i searched and found that httppostedfile has been changed to iformfile but how to handle request.files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is working code from a recent project. Data has been moved from Request.Files to Request.Form.Files. In case you need to convert stream to byte array - this is the only implementation that worked for me. Others would return empty array.

using System.IO;
var filePath = Path.GetTempFileName();
foreach (var formFile in Request.Form.Files)
{
   if (formFile.Length > 0)
   {
      using (var inputStream = new FileStream(filePath, FileMode.Create))
      {
         // read file to stream
         await formFile.CopyToAsync(inputStream);
         // stream to byte array
         byte[] array = new byte[inputStream.Length];
         inputStream.Seek(0, SeekOrigin.Begin);
         inputStream.Read(array, 0, array.Length);
         // get file name
         string fName = formFile.FileName;
      }
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...