0

I have hosted in a shared windows server, I want to save images on the server, and update its path in the database. When I update the path in the database it is looking like something mentioned below,

C:\ClientSites\mydomain.com\mydomain.com\pictures\20210330160946.png

How can I save with the correct URL so that I can use the complete URL for images to display?

var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), @_configuration.GetSection("pictures").Value);

                var file = Request.Form.Files[0];
                if (file.Length > 0)
                {
                    var user = dbContext.User.GetById(1000);

                    var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}";
                    var fullPath = Path.Combine(pathToSave, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    user.ProfilePhotoUrl = fullPath;
                    var result = dbContext.User.Update(user);

                    if (result.Succeeded)
                    {
                        return Json(fullPath);
                    }
                }
John
  • 323
  • 2
  • 15

1 Answers1

0

For serving static files you can use NuGet Microsoft.AspNetCore.StaticFiles and setup its middleware in the startup.cs Configure method:

app.UseStaticFiles(new StaticFileOptions()
{
     FileProvider = new PhysicalFileProvider(@"D:\your\path\with\pictures"),
     RequestPath = new PathString("/pictures")
});

This way, there is no need to save the entire path to the image, only its name. You just put your images during upload into "D:\your\path\with\pictures", and after that, they are accessible on the path "/picture".

To visualize, let me give you the following explanation. Let say that my app is on localhost:24757. If I have a file called some-picture.jpg in the "D:\your\path\with\pictures" I can display it on this URL: localhost:24757/pictures/some-picture.jpg

Michal Rosenbaum
  • 1,801
  • 1
  • 10
  • 18