2

I want to be able to send a file to a MVC VNext webserver.

I've read this article, it works and its all good. But how do it upload a file without using <form>?

The reason for this, is because i want to upload a file without loading a new page.

I've read this article, but it doesn't seem to work. The parameter IFormFile is allways null.

Community
  • 1
  • 1
Assassinbeast
  • 1,207
  • 1
  • 17
  • 33

2 Answers2

4

Try using input type="file" , FormData , $.post()

$.ajaxSetup({processData:false,contentType:false});
$("input[type=file]").change(function() {    
  var data = new FormData(); data.append("file", this.files[0]);
  $.post("/path/to/server", data)
});

alternatively, convert file to JSON object Upload multiple image using AJAX, PHP and jQuery

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
2

Add the input file tag your view.

<form asp-action="Index" asp-controller="Home">   
    <input type="file" id="logo" name="logo" />
    <input type="submit" id="btnSave" />
</form>

We will add some javascript to listen to the submit button event and send the data via ajax.

@section Scripts
{
    <script>
    $(function () {
        $("#btnSave").click(function (e) {
            e.preventDefault();

            var fdata = new FormData();

            var fileInput = $('#logo')[0];
            var file = fileInput.files[0];
            fdata.append("logo", file);

            $.ajax({
                type: 'post',
                url: "@Url.Action("SaveFile","Home")",
                data: fdata,
                processData: false, 
                contentType: false, 
            }).done(function (result) {
                // do something with the result now
                console.log(result);    
            });    
        });
    });
    </script>    
}

And you should have an an action method to accept the file posting

public class HomeController : Controller
{
    private readonly IHostingEnvironment hostingEnvironment;
    public HomeController(IHostingEnvironment environment)
    {
        hostingEnvironment = environment;
    }
    [HttpPost]
    public IActionResult Index(IFormFile logo)
    {
        if (logo != null)
        {
            var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
            var filePath = Path.Combine(uploads, GetUniqueFileName(logo.FileName));
            logo.CopyTo(new FileStream(filePath, FileMode.Create));

        }
        // to do  : Return something
        return RedirectToAction("Index","Home");
    }
    private string GetUniqueFileName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return  Path.GetFileNameWithoutExtension(fileName)
                  + "_" 
                  + Guid.NewGuid().ToString().Substring(0, 4) 
                  + Path.GetExtension(fileName);
    }
}

This will save the file to uploads folder inside wwwwroot directory of your app with a random file name generated using Guids ( to prevent overwriting of files with same name)

Shyju
  • 214,206
  • 104
  • 411
  • 497