显示来自wwwroot文件夹的图像

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

我有一个项目,需要将多个图像存储在wwwroot文件夹中。图像引用保存在数据库中。所以我编写了一个函数来检索图像引用,并循环遍历wwwroot文件夹中保存的图像。

到目前为止,我只能检索文件夹中的第一个图像。不幸的是,其他图像没有被退回。

以下是代码:

  [HttpGet("images")]
        public IActionResult GetImages()
        {
            var results = _context.ImageTable.Select(i => i.ImageNames).ToList();

            foreach (var result in results)
            {
                var folderPath = Path.Combine(_hostingEnvironment.WebRootPath, "imagesFolder", $"{result}.png");

                var file= System.IO.File.ReadAllBytes(folderPath);

                return File(file, "image/jpg");
            }
            return NotFound("No Images");
        }


So what I'm expecting are all the images saved in the wwwroot folder to be displayed.
c# image asp.net-core filestream wwwroot
1个回答
0
投票

Apprach 1:返回一个urls数组并使用javascript在浏览器中创建一系列img

public class HomeController : Controller
{
    private IHostingEnvironment _env;

    // inject a hosting env so that we can get the wwwroot path
    public HomeController(IHostingEnvironment env){
        this._env = env;
    }
    public IActionResult GetImages()
    {
        // get the real path of wwwroot/imagesFolder
        var rootDir = this._env.WebRootPath;
        // the extensions allowed to show
        var filters = new String[] { ".jpg", ".jpeg", ".png", ".gif", ".tiff", ".bmp", ".svg" };
        // set the base url = "/"
        var baseUrl = "/";


        var imgUrls = Directory.EnumerateFiles(rootDir,"*.*",SearchOption.AllDirectories)
            .Where( fileName => filters.Any(filter => fileName.EndsWith(filter)))
            .Select( fileName => Path.GetRelativePath( rootDir, fileName) ) // get relative path
            .Select ( fileName => Path.Combine(baseUrl, fileName))          // prepend the baseUrl
            .Select( fileName => fileName.Replace("\\","/"))                // replace "\" with "/"
            ;
        return new JsonResult(imgUrls);
    }
}

这将返回如下内容:

[
"/imagesFolder/avatar.jpg",
"/imagesFolder/avatar.png",
"/imagesFolder/subFolder/suit-portrait-preparation-wedding-copy.jpg",
"/imagesFolder/subFolder/woman-street-walking-girl.jpg",
"/imagesFolder/subFolder/subFoler2/pexels-photo-copy1.jpg",
"/imagesFolder/subFolder/subFoler2/road-fashion-vintage-bag-copy.jpg"
]

您需要的是向此操作方法发送ajax请求,然后使用这些URL创建相关的<img src={url}>。这是一个使用普通javascript的工作示例:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onload=function(e){
        var urls=JSON.parse(e.target.responseText);
        for(var i = 0 ;i<urls.length;i++){
            var img = document.createElement("img");
            img.src = urls[i];
            document.body.appendChild(img);
        }
    };
    xhr.open("get","/home/getimages");
    xhr.send();
</script>

方法2:使用Razor在服务器端呈现视图:

更改操作方法以返回查看结果:

    public IActionResult GetImages()
    {
        // ...
        return new JsonResult(imgUrls);
        return View(imgUrls);
    }

这里'GetImages.cshtml

@model IEnumerable<string>

<ul>
    @foreach (var url in Model)
    {
        <li><img src="@url" alt="@System.IO.Path.GetFileName(url)"/></li>
    }
</ul>

两者都应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.