使用方法代码在 ASP.NET Core Web API 中创建文件夹 wwroot

问题描述 投票:0回答:1

我正在为我的 Web 应用程序的背面开发 ASP.NET Core Web API,前面是 Angular。我需要在服务器中保存图像或 PDF 等内容并访问它们,因此我想将这些文件保存在

wwwroot
文件夹中,以获得可用于在前端显示它们的 URL。

问题是,当我尝试在保存文件(图像或 PDF)的应用程序(如客户端)中保存图像时,我希望创建

wwwroot
,我尝试使用
Directory.Create
,你可以请参阅屏幕截图。

但是这个文件夹是在特定路径中创建的,但我在我的项目中看不到或在那里保留图像

code

folder of the project

structure of the project

我想为我的 API 创建

wwroot
并将文档保存在我的 API 中,以便在我的 Web 应用程序中使用。

asp.net-core directory asp.net-core-webapi
1个回答
0
投票

如果在 ASP.NET Core Web API 应用程序中保存文件时动态创建“wwwroot”文件夹不存在,您可以修改文件保存方法以确保该文件夹存在。以下是实现这一目标的方法:

[HttpPost("upload")]
public IActionResult UploadFile()
{
    try
    {
        var files = Request.Form.Files;
        if (files == null || files.Count == 0)
            return BadRequest("No files were uploaded.");

        // ensure wwwroot/uploads folder exists
        var uploadsFolder = Path.Combine(_environment.WebRootPath, "uploads");
        if (!Directory.Exists(uploadsFolder))
        {
            Directory.CreateDirectory(uploadsFolder);
        }

        foreach (var file in files)
        {
            var fileName = $"{Guid.NewGuid()}_{file.FileName}";
            var filePath = Path.Combine(uploadsFolder, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            // You can return the file path or URL to access it in the frontend
            var url = Url.Content(Path.Combine("~/uploads", fileName));
            return Ok(new { Url = url });
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"Internal server error: {ex.Message}");
    }

    return BadRequest("Failed to upload files.");
}

确保 Startup.cs 文件中具有以下配置,以启用从“wwwroot”文件夹提供静态文件:

app.UseStaticFiles(); // This enables serving static files like images, CSS, JavaScript, etc. from the wwwroot folder
© www.soinside.com 2019 - 2024. All rights reserved.