I have an Employee Model and Profile Picture. I need to Upload Profile Picture and Model Date both in one POST method. I just need to save Image File Name in Database and Uploading image in a WebRoot Directory.
Here is my Model: public partial class Employers
{
public int EmployerId { get; set; }
public string Companyname { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Password { get; set; }
public string DisplayImage { get; set; }
public bool? IsActive { get; set; }
public DateTime StateDate { get; set; }
}
Here is my Controller Code:
[HttpPost]
public async Task<ActionResult<Employees>> PostEmployees([FromForm] FileUploadAPI Image, [FromBody]Employees employees)
{
try
{
_context.Employees.Add(employees);
await _context.SaveChangesAsync();
await UploadImage(Image, 2, employees.EmployeeId);
var returnInfo = CreatedAtAction("GetEmployees", new { id = employees.EmployeeId }, employees);
return returnInfo;
}
catch(Exception ex)
{
return NoContent();
}
}
public class FileUploadAPI
{
public IFormFile files { get; set; }
}
public async Task<string> UploadImage(FileUploadAPI files, int UserType, int UserId)
{
if (files.files.Length > 0)
{
try
{
if (!Directory.Exists(_hostingEnvironment.WebRootPath + "\\Employees\\"))
{
Directory.CreateDirectory(_hostingEnvironment.WebRootPath + "\\Employees\\");
}
Guid guid = Guid.NewGuid();
string filename = _hostingEnvironment.WebRootPath + "\\Employees\\" + $"EM-{UserType}-UserId-{guid}";
using (FileStream filestream = System.IO.File.Create(filename))
{
await files.files.CopyToAsync(filestream);
filestream.Flush();
return filename;
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
else
{
return "Not Found";
}
}
If i just upload File in POSTMAN without Employee Model, its working fine. But when i pass both File EMployee Data both then FILE is returning null.
Any Suggestion, Solution ?
Thanks