DEV Community

artydev
artydev

Posted on

Upload Files with FormData in .NetCore, without Forms

The code is self explainatory...

Client Side

async function uploadFile() {
  const formData = new FormData();
  const file = new File(["Hello Dev Users"], "devnotes.txt", { type: "text/plain" })
  formData.append("formFile", file);
  try {
    const res = await fetch("/uploadfile", {
      method: "POST",
      body: formData
    });
    return res;
  } catch (ex) {
    console.log(ex);
  }
}
uploadFile().then(r => console.log(r.statusText));
Enter fullscreen mode Exit fullscreen mode

In Controler

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;

namespace file.Controllers
{
  public class FileModel
  {
    public IFormFile FormFile { get; set; }
  }

  [Route("/uploadfile")]
  [ApiController]
  public class FileController : ControllerBase
  {
    [HttpPost]
    public ActionResult Post([FromForm] FileModel file)
    {
      try
      {
        string fileName = file.FormFile.FileName;

        string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", fileName);

        using (Stream stream = new FileStream(path, FileMode.Create))
        {
          file.FormFile.CopyTo(stream);
        }

        return StatusCode(StatusCodes.Status201Created);
      }
      catch (Exception)
      {
        return StatusCode(StatusCodes.Status500InternalServerError);
      }
    }

  }
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)