0

Environment: ASP.NET Web API .NET Core 2.1

I just started working on ASP.NET Web API and stuck in uploading base64 image. Here is my code:

public bool UploadFile(string base64String)
    {
        try
        {
            var folderName = Constant.PATH_ITEM_IMAGES;

            string defaultImagePath = HostingEnvironment.MapPath("~/images");

            byte[] bytes = Convert.FromBase64String(base64String);

            using (MemoryStream ms = new MemoryStream(bytes))
            {
                Image pic = Image.FromStream(ms);

                pic.Save(defaultImagePath);
            }

            return true;
        }
        catch(Exception ex)
        {
            return false;
        }
    }

Both HostingEnvironment.MapPath("~") or Server.MapPath does not work. Also, Image cannot be found

I'm using Nuget Package manager to manage dependencies. What am I missing here? Any package I need to add?

This did not help either:

System.Web.HttpContextBase' does not contain a definition for 'Current' MVC 4 with Elmah Logging

Ashutosh
  • 4,371
  • 10
  • 59
  • 105

1 Answers1

0

Use HttpContext.Current.Server.MapPath

public bool UploadFile(string base64String)
    {
        try
        {
            var folderName = Constant.PATH_ITEM_IMAGES;
            string defaultImagePath = HttpContext.Current.Server.MapPath("~/images/");

            byte[] bytes = Convert.FromBase64String(base64String);

            using (MemoryStream ms = new MemoryStream(bytes))
            {
                Image pic = Image.FromStream(ms);
                string imageName  = "";//get image name (pic.png)
                string picPath = defaultImagePath  + imageName;
                pic.Save(defaultImagePath);
            }

            return true;
        }
        catch(Exception ex)
        {
            return false;
        }
    }

and when try save image give it name and combine it with target folder.

Eng Hazymeh
  • 147
  • 4