the server process must have access to the folder. then use the Directory.GetFiles to get the list. use the <img> tag to display an image. if the images are small, you can use data urls for the img src, or supply a webapi controller action to return the image. you could also configure the static file handler to allow urls to the images.
Dynamic tile list in blazor for showing the images of a folder?
Hello
Is there any way to make a tile list to show the images of a folder dynamically in Blazor server? (without connecting to the database?)
thanks
2 answers
Sort by: Most helpful
-
-
Zhi Lv - MSFT 32,021 Reputation points Microsoft Vendor
2022-10-07T02:44:52.793+00:00 Hi @Saeed Pooladzadeh ,
Is there any way to make a tile list to show the images of a folder dynamically in Blazor server? (without connecting to the database?)
I assume you want to list the images folder in the
wwwroot
folder, if that is the case, you could refer to the following sample:- Create a ImageModel to store the image name and image path:
public class ImageModel { public string Name { get; set; } public string Path { get; set; } public string Type { get; set; } }
- Create a service and use Directory.GetFiles method to get all files:
public interface IImageRespository { List<ImageModel> GetImages(); } public class ImageRepository : IImageRespository { private readonly IWebHostEnvironment _env; public ImageRepository(IWebHostEnvironment webHostEnvironment) { _env = webHostEnvironment; } public List<ImageModel> GetImages() { string[] filePaths = Directory.GetFiles(Path.Combine(_env.WebRootPath, @"images")); List<ImageModel> imagelist = new List<ImageModel>(); foreach (string filePath in filePaths) { var img = new ImageModel(); img.Path = @"images/" + Path.GetFileName(filePath); img.Name = Path.GetFileName(filePath); img.Type = Path.GetExtension(filePath); imagelist.Add(img); } return imagelist; } }
- Register the Services in the Program.cs file:
builder.Services.AddScoped<IImageRespository, ImageRepository>();
- Create a Razor Component to display the images: 248299-sourcecode.txt
- Then, the output as below:
More detail information about work with images in ASP.NET Core Blazor, see Dynamically set an image source and Stream image data(If you want to dynamic get image from URL, you can check this article).
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.Best regards,
Dillion - Create a ImageModel to store the image name and image path: