Ganesh Ayer
Ganesh Ayer

Reputation: 15

How to upload image with other form control (Angular 8) and asp.net core api

        I want fill form which have upload profile image and other controls like Name,address 
        I am using angular 8 for client side and asp.net core for backend..
        I want viewmodel which contains all properties.

I have used angular8 for uploading image in formdata.I have gone through https://www.techiediaries.com/angular-formdata/.My main question is how to receive uploaded file in ViewModel not in httpRequest.Form.Files["ImageFile"]

[HttpPost("Create")]
public IActionResult CreateApplication(ApplicationModel model)
 {
         //want to capture uploaded image 
            return Ok();
  }

Upvotes: 0

Views: 433

Answers (2)

Yanayaya
Yanayaya

Reputation: 2184

Ok got it, the problem was that the directory names were not fixed, they were created by the newly created Id of the product, so the solution was to carry out a check for the directory and if it's not there, create it.

For example

if (!Directory.Exists(folderName))
{
    Directory.CreateDirectory(folderName);
}

Once it's created with the new Id it can be used/found.

Upvotes: 0

Mateech
Mateech

Reputation: 1064

See this tutorial, can be very helpful: Click

Here is way how i`d do it:

[HttpPost]       
    public async Task<IActionResult> AddBodyType([FromForm]ApplicationModel model)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            else
            {
                var file = Request.Form.Files[0];
                var folderName = Path.Combine("Resources", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    var dbPath = Path.Combine(folderName, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                        await stream.FlushAsync();
                    }

                    model.ImagePath = dbPath;
                    await _context.Add(model);

                    return Ok();
                }
                else
                {
                    return BadRequest();
                }
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }

Upvotes: 1

Related Questions