首页 > 数据库 > 数据库开发技术 > 在ASP.NET Core 中上传文件
ASP.NET Core 支持使用缓冲的模型绑定(针对较小文件)和无缓冲的流式传输(针对较大文件)上传一个或多个文件。
1.上传是支持上传任何文件的,图片只是上传的一种。
2.根据扩展名进行区分你所上传的文件形式。
Install-Package Microsoft.AspNetCore.StaticFiles
services.AddDirectoryBrowser();
app.UseStaticFiles();
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\uploads")),
RequestPath = new PathString("/Uploads"),
EnableDirectoryBrowsing = true
});
在 wwwroot 目录下创建一个名为 uploads 的文件夹,用来存放上传文件
在项目中添加一个上传文件的表单,如下:
<form action="/Home/UploadFile" enctype="multipart/form-data" method="post">
<input type="file" name="file" />
<input type="submit" value="上传" />
</form>
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("文件不能为空");
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return RedirectToAction("Index");
}
原文作者:后端Q;如有侵权,请联系管理员删除。