ASP.NET Core 2.1 文件上传实践指南

c程序员 by:c程序员 分类:C# 时间:2024/09/05 阅读:11 评论:0

ASP.NET Core 2.1是微软推出的最新版本的 .NET Core 框架,它提供了许多新的功能和改进,其中包括对文件上传的支持。在本文中,我们将深入探讨如何在 ASP.NET Core 2.1 中实现文件上传功能,并提供一些实用的技巧和最佳实践。

准备工作

在开始之前,我们需要确保已经安装了最新版本的 Visual StudioVisual Studio Code,并且已经创建了一个新的 ASP.NET Core 2.1 项目。如果您还没有这样做,请先完成这些步骤。

创建文件上传表单

首先,我们需要在视图中创建一个用于文件上传的表单。在 ASP.NET Core 2.1 中,我们可以使用 IFormFile 接口来处理上传的文件。下面是一个示例代码:

Views/Home/Index.cshtml

<form asp-controller="Home" asp-action="UploadFile" enctype="multipart/form-data">
    <div class="form-group">
        <label for="file">选择文件</label>
        <input type="file" class="form-control-file" id="file" name="file" required>
    </div>
    <button type="submit" class="btn btn-primary">上传</button>
</form>

处理文件上传

接下来,我们需要在控制器中编写处理文件上传的代码。在这个示例中,我们将把上传的文件保存到服务器的 wwwroot/uploads 目录中。

Controllers/HomeController.cs

[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    if (file != null && file.Length > 0)
    {
        var uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads");
        if (!Directory.Exists(uploads))
        {
            Directory.CreateDirectory(uploads);
        }

        var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
        var filePath = Path.Combine(uploads, fileName);

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await file.CopyToAsync(fileStream);
        }

        return RedirectToAction("Index");
    }

    return View();
}

配置文件上传设置

在某些情况下,您可能需要配置文件上传的设置,例如限制文件大小或允许的文件类型。您可以在 Startup.cs 文件中的 ConfigureServices 方法中进行这些设置。

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<IISServerOptions
非特殊说明,本文版权归原作者所有,转载请注明出处

本文地址:https://chinaasp.com/2024095414.html


TOP