0

Am trying to save the images to the database using the asp.net webapi. In this controller am saving the image into my /Content/Banner/ Folder.

[HttpPost]
        [Route("PostBanner")]
        [AllowAnonymous]
        public HttpResponseMessage PostBannerImage()
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            try
            {
            var httpRequest = HttpContext.Current.Request;

            foreach (string file in httpRequest.Files)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

                var postedFile = httpRequest.Files[file];
                if (postedFile != null && postedFile.ContentLength > 0)
                {

                    int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  

                    IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                    var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    if (!AllowedFileExtensions.Contains(extension))
                    {

                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else if (postedFile.ContentLength > MaxContentLength)
                    {

                        var message = string.Format("Please Upload a file upto 1 mb.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else
                    {
                        var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
                        postedFile.SaveAs(filePath);
                    }
                }

                var message1 = string.Format("Image Updated Successfully.");
                return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
            }

            var res = string.Format("Please Upload a image.");
            dict.Add("error", res);
            return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
        catch (Exception ex)
        {
            var res = string.Format("some Message");
            dict.Add("error", res);
            return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
    }

Now what i need to send this filePath to database. I know i just need to pass this file path to the following service controller. But i dont know how to pass it. could anyone help me to solve this problem.

This Is my services.cs

 public async Task<int?> Addbanner(DisplayBannersDto dto)
        {
            try
            {
                var d = _dbContext.Banners
            .FirstOrDefault();



                d.Banner_Description = dto.Description;
                d.Banner_Location = dto.Location;


                //mark entry as modifed
                _dbContext.Entry(d).State = EntityState.Modified;
                await _dbContext.SaveChangesAsync();
                return d.Banner_Id;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

This is my controller

[HttpPost]
        [Route("AddBanner")]
        public async Task<IHttpActionResult> AddBanner(DisplayBannersDto dto)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            int? result = await _service.Addbanner(dto);
            return Ok();

        }
7
  • Do you want to save the image path from inside of the PostBannerImage() API or do you want to invoke a second API to do the database saving? Commented Apr 6, 2017 at 5:20
  • @JoseFrancis i want to invoke a second API to do the database saving.. Commented Apr 6, 2017 at 5:25
  • So, why don't you return the "filepath" from the PostBannerImage(), receive at the client then call the second API after inserting the same to DisplayBannersDto. Commented Apr 6, 2017 at 5:31
  • am new to the asp.net how can i do that? can u help me to solve this? Commented Apr 6, 2017 at 5:33
  • Did that work ? Commented Apr 6, 2017 at 6:58

1 Answer 1

1

Change your else condition like below:

else
{
    var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
                        postedFile.SaveAs(filePath);

    return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Created,
                Content = new StringContent(filePath, Encoding.UTF8, "application/json")
            };
}

Now, you have the filepath in the content of the API response.

and use that response like :

var displayBannersDto = new DisplayBannersDto();
displayBannersDto.Banner_Location = response.Content.ToString();

then call your AddBanner() API with displayBannersDto as the dto.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.