Search code examples
databaseapiasp.net-core-webapiform-post

Posting Model WEB API NET CORE 6


public partial class Thongtin
{
    public string? Id { get; set; }

    public string? Hovaten { get; set; }

    public string? Sodienthoai { get; set; }

    public string? Diachilapdat { get; set; }

    public string? Tenhinhanh { get; set; }

    public string? Hinhanh { get; set; }
}

 public IActionResult Upload(IFormFile file, Thongtin a )
        {
            if (file != null)
            {
                var uniqueFileName = GetUniqueFileName(file.FileName);


                var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
                var filePath = Path.Combine(uploads, uniqueFileName);
                file.CopyTo(new FileStream(filePath, FileMode.Create));
            }
        


            return Ok("upload successfull");
        }

This is my reseult when i put object and type IFORMFile

The result not have object enter image description here

 public IActionResult Upload(  IFormFile file)
        {
            if (file != null)
            {
                var uniqueFileName = GetUniqueFileName(file.FileName);


                var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
                var filePath = Path.Combine(uploads, uniqueFileName);
                file.CopyTo(new FileStream(filePath, FileMode.Create));
            }
        


            return Ok("upload successfull");
        }

Because i want to save text and image name to database and file image to forder source code

I want to get form upload and object same time in method post


Solution

  • You can extend the Thongtin class with the IFormFile type. Then using 1 parametr for the API with [Consumes("multipart/form-data")] and [FromForm] attribute.

    public class Thongtin
        {      
            public string? Id { get; set; }
            public IFormFile? file { get; set; }
            public string? Hovaten { get; set; }
            public string? Sodienthoai { get; set; }
            public string? Diachilapdat { get; set; }
            public string? Tenhinhanh { get; set; }
            public string? Hinhanh { get; set; }
        }
    
            [HttpPost]
            [Consumes("multipart/form-data")]
            public IActionResult Upload([FromForm] Thongtin a)
            {
                if (a.file != null)
                {
                    var uniqueFileName = GetUniqueFileName(a.file.FileName);
                    var uploads = Path.Combine(Environment.WebRootPath, "Uploads");
                    var filePath = Path.Combine(uploads, uniqueFileName);
                    a.file.CopyTo(new FileStream(filePath, FileMode.Create));
                }
                return Ok("upload successfull");
            }
    

    Then you can post file and parameters at the same time
    enter image description here enter image description here