Submit a Form using AJAX in ASP.Net Core MVC

前端 未结 2 1989
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 10:29

I am working with ASP.Net Core 2.1, and trying to upload a file while returning it\'s url, without refreshing the page.

I am trying to write the JavaScript in site.js a

2条回答
  •  野的像风
    2021-02-03 11:28

    Unfortunately the jQuery serialize() method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).

    What you may do is, create a FormData object, append the file(s) to that. When making the ajax call, you need to specify processData and contentType property values to false

    and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.

    $(function () {
        $("#FileUploadForm").submit(function (e) {
            e.preventDefault();
    
            console.log('Doing ajax submit');
    
            var formAction = $(this).attr("action");
            var fdata = new FormData();
    
            var fileInput = $('#uploadfile')[0];
            var file = fileInput.files[0];
            fdata.append("file", file);
    
            $.ajax({
                type: 'post',
                url: formAction,
                data: fdata,
                processData: false,
                contentType: false
            }).done(function (result) {
                // do something with the result now
                console.log(result);
                if (result.status === "success") {
                    alert(result.url);
                } else {
                    alert(result.message);
                }
            });
        });
    })
    

    Assuming your server side method has a parameter of with name same as the one we used when we created the FormData object entry(file). Here is a sample where it will upload the image to the uploads directory inside wwwwroot.

    The action method returns a JSON object with a status and url/message property and you can use that in the success/done handler of the ajax call to whatever you want to do.

    public class HomeController : Controller
    {
        private readonly IHostingEnvironment hostingEnvironment;
        public HomeController(IHostingEnvironment environment)
        {
            _context = context;
            hostingEnvironment = environment;
        }
        [HttpPost]
        public async Task Upload(IFormFile file)
        {
            try
            {
                var uniqueFileName = GetUniqueFileName(file.FileName);
                var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
                var filePath = Path.Combine(uploads, uniqueFileName);
                file.CopyTo(new FileStream(filePath, FileMode.Create));
                var url = Url.Content("~/uploads/" + uniqueFileName);
                return Json(new { status = "success", url = url });
            }
            catch(Exception ex)
            {
                // to do : log error
                return Json(new { status = "error", message = ex.Message });
            }
        }
        private string GetUniqueFileName(string fileName)
        {
            fileName = Path.GetFileName(fileName);
            return Path.GetFileNameWithoutExtension(fileName)
                      + "_"
                      + Guid.NewGuid().ToString().Substring(0, 4)
                      + Path.GetExtension(fileName);
        }
    }
    

提交回复
热议问题