問題描述
我正在嘗試使用 ajax 請求使用 aspnet 核心上傳文件.在以前版本的 .net 中,我曾經(jīng)使用
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;
(...)
但現(xiàn)在它在 request.files 處顯示錯誤我怎樣才能讓它工作?搜了一下發(fā)現(xiàn)httppostedfile已經(jīng)改成了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?
推薦答案
這是來自最近項目的工作代碼.數(shù)據(jù)已從 Request.Files 移至 Request.Form.Files.如果您需要將流轉(zhuǎn)換為字節(jié)數(shù)組 - 這是唯一對我有用的實現(xiàn).其他人會返回空數(shù)組.
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;
}
}
}
這篇關(guān)于ASP.NET CORE 中的 Request.Files的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!