【问题标题】:Displaying images from wwwroot folder显示来自 wwwroot 文件夹的图像
【发布时间】:2019-04-27 02:00:42
【问题描述】:

我有一个项目需要将多个图像存储在 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.

【问题讨论】:

  • 通常 1 个 http 请求需要 1 个图像,除非您的客户端知道如何处理多个图像。我不认为你正在为一个特殊的客户做这个,所以每个请求返回 1 张图片。
  • 我不确定我是否理解你所说的。我所拥有的是我正在迭代的图像结果列表。我认为这与 foreach 循环中的返回文件有关。话虽如此,我需要一个解决方案来解决我的问题。
  • 你想在这里实现什么?使用File 将返回文件的实际内容。也许您想渲染一个包含图像文件链接的图像列表?
  • @HenkMollema 感谢您的来信。我想要实现的是渲染来自 wwwroot 文件夹的图像。在我的数据库中,图像被引用为 img01、img02、img03 等。因此在该方法中,我正在检索所有图像并尝试在浏览器中显示所有图像。希望这是有道理的。

标签: c# image asp.net-core filestream wwwroot


【解决方案1】:

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>

方法二:使用 Razor 在服务器端渲染视图:

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

公共 IActionResult GetImages() { // ... return new JsonResult(imgUrls); 返回视图(imgUrls); }

这里是GetImages.cshtml

@model IEnumerable<string>

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

两者都应该工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多