How to Display a List of Images, from a Folder on Hard Drive, on ASP.NET Website

How do you display a list of images, from a folder on hard drive, on ASP.NET website?

First you need to place the images you want to display under the web tree. Let's assume you have done that and they are in folder called Images. You can then use a Repeater control to display them by data-binding it like so:

Something like this...

<asp:Repeater ID="RepeaterImages" runat="server">
<ItemTemplate>
<asp:Image ID="Image" runat="server" ImageUrl='<%# Container.DataItem %>' />
</ItemTemplate>
</asp:Repeater>

And then in your code behind:

protected void Page_Load(object sender, EventArgs e)
{
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Images"));
List<String> images = new List<string>(filesindirectory.Count());

foreach (string item in filesindirectory)
{
images.Add(String.Format("~/Images/{0}", System.IO.Path.GetFileName(item)));
}

RepeaterImages.DataSource = images;
RepeaterImages.DataBind();
}

This basically creates an array of images with their full path from the directory.
It then creates a List of strings that contain the virtual path to the image.
It then binds that List to the repeater, which displays each item in it's template, which is an Image control which uses the path as the ImageUrl. It's quick'n'dirty, but works and should be a good starting point.

Display image stored in different hard drive

The safest way would be to create in IIS a virtual directory where the files are stored. The virtual directory can point to any location (Physical, UNC, etc) that IIS supports, so you have the most flexibility, and as far as security concerns are for uploading and managing the files, even if the files are on another server, you won't run into application permission elevation issues - you will still need to make sure that the appropriate users have read/write permissions.

Creating Virtual Directory in IIS

Accessing the virtual directories in c#:

Deprecated API: Server.MapPath("~/VirtualDir/");

Current API: HostingEnvironment.MapPath("~/VirtualDir/");

asp.net core 2 load and display images from local disk drive

In most cases, the most secure (and easiest) optin is to store images under the site's root folder to avoid giving the web site's account access outside the site folder itself.

User profile images aren't static though. That's why they're often stored in a database or other storage.

You can map a specific request path to a custom location in UseStaticFiles. From the documentation example :

public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder

app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
RequestPath = "/StaticFiles"
});
}

The first call configures wwwroot as the root for static files. The second call overrides this for requests starting with /StaticFiles and points to a folder called MyStaticFiles under the application's folder.

You could expose all profile pictures under the avatar path with this code:

public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles(); // For the wwwroot folder

app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
"X:\game_data\avatars\"),
RequestPath = "/avatars"
});
}

A better option would be to load the location from a configuration file.

Another consideration is that simply mapping the folder to a path will allow anyone to read profile pictures if they can guess their name. This may or may not be a concern.

If it is, you use a controller that only returns the current user's as a FileResult, eg:

class AvatarsController
{
[HttpGet]
public async Task<IActionResult> Get()
{
var userID=SomehowFindTheCurrentUserID();
var avatarPath= Path.Combine(_avatarRoot,$"{userID}.jpeg");
return File(avatarPath, "image/jpeg");
}
}

How to display image which is stored in local drive?

You will have problems with permissions if the image is outside of the web site folder. Traditionally, web sites run under the NETWORK SERVICE user account, which will limit access to files outside of the folder. You will need to extract the file from a folder with similar access and it is extremely unwise to do so, particularly from Program Files.

You should possibly proxy the file via a web page or web service, which doesn't expose the fact that the image is served external to the web site. You'll need to make sure the target folder C:\Program Files\Adrenalin\Adrenalin\UploadedFiles\TemplateFile has NETWORK SERVICE Read-access.

eg. create a blank ASP.NET page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageServer.aspx.cs" Inherits="ImageServer" %>

with the code behind:

class ImageServer
{
void Page_Load(object sender, EVentArgs e)
{
Response.ContentType="image/jpeg"; // for JPEG file
string physicalFileName=@"C:\Program Files\Adrenalin\Adrenalin\UploadedFiles\TemplateFile\abc.jpg";
Response.WriteFile(physicalFileName);
}
}

And test in your browser by going to the URL

http://<localhost>/<website>/ImageServer.aspx

You should get the image.

Then, within the tag, use the URL of the page as your image placeholder:

<img src="ImageServer.aspx" alt="Image served" />

UPDATE:

Looking at your latest comments, I suggest you send a QueryString parameter with some sort of employee code and use that to query the database and get the appropriate filename within the Page_Load() method. Don't send the filename as part of the QueryString.

How to display image which is stored on Local drive or network drive?

1) Why the proxy page can access the physical path but other page cannot able to access it ?

The other page can. However, the other page isn't accessing the file. It's just setting the file's path to the HTML output for the client (web browser) to access it. Resulting in this:

<img src = "C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg" />

Since the user doesn't have access to that file, the img tag won't work. The purpose of the "proxy" page is to serve the content of the file from a location which the user can access, that location being the proxy page.

2) And is there any other way to do it ?

Nope. Either the user has to have direct access to the file via some virtual path on the web server, or you have to have a proxy which reads the file's contents and sends it to the user. It has little to do with your C# code and everything to do with what the user can see on the web server. Unless the file is in a web-accessible folder, the user can't see it.

This is a very common and standard approach to securing files behind a web application. Sometimes, for example, you want to check the user's authorization before allowing them to see a file. If the file were publicly accessible, they could just go to it directly. But if there's a proxy page between the user and the file then that page can enforce authorization.

How to list some specific images in some folder on web server?

The best way is to just loop through all the files in the directory.

While dbRead.Read
dim sUserId as String= dbread('user_id')
For Each sFile As String In IO.Directory.GetFiles("C:\")
if sFile.StartsWith (sUserId) Then
'Do something.
End If
Next
Loop

However, to actually show the images, you're best bet could be to create a datatable of these images, and then use a datalist or repeater control to display them.

Dim dtImages as new DataTable
dtImages.Columns.Add("Filename")
If dbRead.Read
dim sUserId as String= dbread('user_id')
For Each sFile As String In IO.Directory.GetFiles("C:\")
if sFile.StartsWith (sUserId) Then
Dim drImage as DataRow = dtImages.NewRow
drImage("Filename") = sFile
dtImages.Rows.add(drImage)
End If
Next
End If
dlImages.DataSource = dtImages
dlImages.DataBind

Then, on your ASPX page, you would have a datalist control called dlImages defined like:

    <asp:datalist id="dlImages" RepeatDirection="Horizontal" runat="server" RepeatLayout="Flow" Height="100%">
<ItemTemplate>
<asp:Image ID="Image1" Runat=server ImageUrl='<%# Server.MapPath("photos") & Container.DataItem("FileName") %>'>
</asp:Image>
</ItemTemplate>
</asp:datalist>

Image not displayed read from the system hard disk

To run the application the user has to create a folder called attachments in his c drive.

This statement is somewhat ambiguous, but hopefully it means that the user installing your application must create a C:\Attachments folder on the same machine as your Web application. If that's the case, then the simplest solution is to open IIS Manager, right-click your application folder and add a virtual directory with the following settings:

  • Alias: Attachments
  • Physical path: C:\Attachments

The virtual directory will look like this:

screenshot of IIS

Then, in your .aspx page, just set the ImageURL property of your Image control to an app-relative URL:

this.ImageID.ImageUrl = "~/Attachments/test.jpg";

(You don't need to resolve the URL yourself. The Image control will resolve the ~ to an appropriate URL relative to the current request, and IIS will map the absolute URL sent by the browser to the C:\Attachments folder.)


However, if instead you meant to say that every visitor to your site must create a C:\Attachments folder on his or her own machine, then you should re-evaluate what you're trying to do: Browser security settings do not allow Web pages to access resources stored locally on client machines.



Related Topics



Leave a reply



Submit