Home > database >  How to access images directory outside of the Asp.Net Core Project
How to access images directory outside of the Asp.Net Core Project

Time:02-01

I'm trying to serve images from a directory outside of the current ASP.NET Core 6 project that I'm working with and none of the images are showing. I've read the enter image description here

CodePudding user response:

What do you get for the img's src attribute after the @Url.Content() call? That is, what address is actually rendered to the browser as part of the final html?

If the address still starts with C:\Development, something isn't right. The address in the image element's src attribute resolves from the perspective of the user's browser, not your web server, so it needs to look something more like this:

https://example.com/classic-site/websiteImages/Images/ItemImages/10001234.jpg

Then in your application, if the the classic site is no longer online on it's own you need to able to receive a request for that address and map to the right place so it serves the right file.

You have to be careful testing this, because very often during development the server and browser run on the same computer. In that scenario, an address like C:\Development\Website... might seem to work just fine in the web browser, but it will fail as soon as you start hosting the application on it's own server, away from the end user's browser.

CodePudding user response:

Since you've already configured the statifiles middleware to provide files from that specific folder, this should work:

 <img src="~/10001234.jpg" />

So as long as you generate URLs in this form: ~/{fileName} you should be good.

Here is the main documentation on serving files outside of the project folder structure:

CodePudding user response:

In ASP.NET Core, you can access images or other files stored outside of the project directory by using a path that is relative to the root of the file system. This is typically done by using the Path.Combine method to combine the root path of the file system with the path to the desired file.

Here's an example that demonstrates how to access an images directory located outside of the project directory:

using System.IO;

// Get the root path of the file system
string rootPath = Path.GetPathRoot(Directory.GetCurrentDirectory());

// Combine the root path with the path to the images directory
string imagesDirectory = Path.Combine(rootPath, @"MyImages");

// Get a list of all the files in the images directory
string[] imageFiles = Directory.GetFiles(imagesDirectory);

// Loop through each file and display its name
foreach (string file in imageFiles)
{
Console.WriteLine(Path.GetFileName(file));
}

Note that when accessing files outside of the project directory, it is important to consider security and permissions. You may need to ensure that the user account that the ASP.NET Core application is running under has the necessary permissions to access the files.

  • Related