I am struggling with uploading a picture inside a folder in asp.net core. I have the following model class:
public class User
{
public int IdUser { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfPassword { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public DateTime? Dob { get; set; }
public byte[] Picture { get; set; }
public virtual ICollection<Login> Login { get; set; }
}
This is the post method in the API controller:
[HttpPost]
public async Task<string> Post(IFormFile file,User user)
{
string fName = file.FileName;
string path = Path.Combine(_environment.ContentRootPath, "uploads/" + fName);
using (var stream = new MemoryStream())
{
using(var fileStream=new FileStream(path, FileMode.Create))
{
await stream.CopyToAsync(fileStream);
user.Picture = stream.ToArray();
string s = Convert.ToBase64String(user.Picture);
return s;
}
}
}
I have declared an IFormFile file
in the method which I convert to byte array and I add the path where the image has to be saved. Every time I'm trying to post the image as binary in Postman it returns
415 Unsupported Media type
and if I try as a form-data it will return
System.NullReferenceException: Object reference not set to an instance of an object
The client side actually stores the image file as a byte array in the database, but I need to save it in the folder on the server-side. Can someone help me understand why it keeps returning the null exception? What am I doing wrong?