ASP.NET CORE中的Request.Files [英] Request.Files in ASP.NET CORE
问题描述
我正在尝试使用ajax request使用aspnet core上传文件。
在以前的.net版本中,我曾经使用
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;
(...)
但现在它在request.files中显示错误得到它的工作?我搜索发现httppostedfile已更改为iformfile,但是如何处理request.files?
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?
推荐答案
最近的项目。数据已从 Request.Files 移至 Request.Form.Files 。
如果您需要将流转换为字节数组-这是唯一对我有用的实现。其他人将返回空数组。
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;
}
}
}
这篇关于ASP.NET CORE中的Request.Files的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!