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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.