我是ASP.net Core的新手,我想上传一个文件(一张图片)并将其存储在特定文件夹中。我一直在按照此教程进行操作(ASP.NET Core中的文件上传),但我不知道如何将其存储在文件中,它只是被上传到服务器上。
<form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Index">
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
这是控制器
[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});
}
这是我正在使用的类
public interface IFormFile
{
string ContentType { get; }
string ContentDisposition { get; }
IHeaderDictionary Headers { get; }
long Length { get; }
string Name { get; }
string FileName { get; }
Stream OpenReadStream();
void CopyTo(Stream target);
Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}
我只需要将图片存储在文件夹中,例如:C:\Users\DESKTOP-1603\Desktop\GestionSyndic\GestionSyndic\src\WebApplication1\wwwroot\images\并更改图片的名称。谢谢:D
IFormFile.OpenReadStream()
和 ImageSharp 来验证它是否为真实的图像文件。如果您不需要此功能,可以使用以下方法:https://dev59.com/B3RC5IYBdhLWcg3wFdJx - DogeAmazed