Home > Blockchain >  How to Save an uploaded Image Url in ASP.Net Core?
How to Save an uploaded Image Url in ASP.Net Core?

Time:06-12

I'm uploading an image as a part of the user model, and I should save the image url to display the image in the REST Client (link like "localhost/Images/ImageName.png"), so I saved the Image in the wwwroot this in the Post Api:

 [HttpPost]
        public async Task<String> Post([FromForm]Machine mach)
        {
            try
            {
                if (mach.Files.Length > 0)
                {
                    {
                        FileInfo fi = new FileInfo(mach.Files.FileName);
                        var newfilename = "Image_"   DateTime.Now.TimeOfDay.Hours   fi.Extension;
                        var path = Path.Combine(hostingEnvironment.WebRootPath  "\\Images\\"   newfilename);
                       /* var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Images");*/
                     
                        using (var stream = new FileStream(path, FileMode.Create))
                        {
                            mach.Files.CopyTo(stream);
                        }

                        Machine machine = new Machine();

                        mach.ImagePath = path;
                        
                        _context.machines.Add(mach);
                        _context.SaveChangesAsync();

                    }
                    return ("saved");

                }

I saved the model correctly but I got the url like this:

"imagePath": "C:\Users\amyra\source\repos\MyApi\wwwroot\Images\Image_18.png"

I tried to display the image by "localhost:port/Images/.." but I got page not found.

CodePudding user response:

Check your application's startup and make sure the app.UseStaticFiles(); line is there. Typically it should come after app.UseHttpsRedirection(); and before app.UseAuthorization

The default API template doesn't have this line.

Edit: To save the URL of the image instead of the physical file path

mach.ImagePath  = new UriBuilder
{
    Scheme = Request.Scheme,
    Host = Request.Host.Host,
    Port = Request.Host.Port ?? -1,
    Path = "/Images/"   newfilename
}.ToString();

Though I wouldn't recommend saving the host/port/scheme part of the URL in the database as these may be subject to change.

Rather I recommend saving only the Path part

mach.ImagePath = "/Images/" newfilename;

You can add the host/port/scheme part when serving the data to clients.

  • Related