[英]Alternative of HttpPostedFileBase in asp.net core and name of namespace
[英]'HttpPostedFileBase' in Asp.Net Core 2.0
我最近正在開發一個 ReactJS 應用程序,該應用程序調用 API(使用 .NET Core 2.0 開發)。
我的問題是如何在 .NET Core 2.0 API 中使用HttpPostedFileBase
以獲取文件內容並將其保存在數據庫中。
您在 ASP.NET Core 2.0 中沒有HttpPostedFileBase
,但您可以使用IFormFile
。
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
更多信息: https : //docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1
IFormFile
位於以下命名空間Microsoft.AspNetCore.Http
。
ASP.NET Core 中不存在HttpPostedFileBase
。 您現在應該改用IFormFile
。 但是,這僅在您將請求作為multipart/form-data
發送時才有效,如果您使用像 React 這樣的客戶端框架,您可能不會這樣做。 如果您要發布 JSON,您應該使用編碼為 Base64 字符串的文件設置與您的文件屬性對應的 JSON 成員。 服務器端,您應該綁定到byte[]
。
您還應該能夠獲得這樣的文件:
[HttpPost]
public ActionResult UploadFiles()
{
var files = Request.Form.Files;
return Ok();
}
如果有人通過搜索HttpPostedFileBase
發現了這一點,那么您可能熟悉編寫 ASP.NET 控制器方法,如下所示:
public async Task<IActionResult> DoThing(MyViewModel model, HttpPostedFileBase fileOne, HttpPostedFileBase fileTwo)
{
//process files here
}
如果您想在 ASP.NET Core 中編寫等效項,則可以這樣編寫:
public async Task<IActionResult> DoThing(MyViewModel model, IFormFile fileOne, IFormFile fileTwo)
{
//process files here
}
即方法簽名所需的唯一更改是用IFormFile
替換HttpPostedFileBase
。 然后您需要修改您的方法以使用新的參數類型(例如HttpPostedFileBase
有一個InputStream
屬性,而IFormFile
有一個OpenReadStream()
方法),但我認為這些差異的細節超出了這個問題的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.