Как отправить данные управления загрузкой в JQuery AJAX без плагинов

0

Я пытаюсь загрузить файл/файлы на сервер через Ajax-запрос в MVC, но файл всегда возвращает null в контроллере, можете ли вы предложить способ передачи данных файла в запрос ajax?

<form method="post" enctype="multipart/form-data">
<div>
    @Html.AntiForgeryToken()
    <input type="file" name="file" id="files" multiple><br>
    <input type="button" value="Upload File to Server" id="submit">
</div>
</form>

<script type="text/javascript">
$("#submit").click(function () {
        var formData = $('#files').val();
        alert(formData);
        $.ajax({
            url: 'home/index',
            type: 'POST',
            datatype: 'json',
            enctype: "multipart/form-data",
            data: { file: formData },
            //processData: false, // Don't process the files
            //contentType: false, // Set content type to false as jQuery will tell the server its a query string request
            success: function (data) {
                alert(data);
            },
            error: function () {
                alert("failed");
            }
        });
    });
</script>


[HttpPost]
    [ActionName("Index")]
    public ActionResult Index_Post(HttpPostedFileBase file)
    {
        string errormsg = string.Empty;
        if (file != null)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // TODO: need to define destination
                var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                try
                {
                    file.SaveAs(path);
                    errormsg = "uploaded";
                    return Json(fileName + errormsg);
                }
                catch
                {
                    errormsg = "failed to upload";
                    return Json(fileName + errormsg);
                }
            }
        }

        else
        {
            errormsg = "No file selected";
            return Json(errormsg);
        }
        return View();
    }   
}
Теги:
asp.net-mvc

1 ответ

0

Возьмите обычную кнопку вместо кнопки отправки и попробуйте под кодом

 $("#submit").click(function () {
                var formData = new FormData();
                var opmlFile = $('#myFile')[0];
                formData.append("opmlFile", opmlFile.files[0]);

                $.ajax({
                url: 'home/index',
                type: 'POST',
                datatype: 'json',
                enctype: "multipart/form-data",
                data:  formData ,
                //processData: false, // Don't process the files
                //contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                success: function (data) {
                    alert(data);
                },
                error: function () {
                    alert("failed");
                }
            });
            });
        });

и действия контроллера: -

[HttpPost]
    [ActionName("Index")]
    public HttpResponseMessage Index()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;

            // Check if files are available
            if (httpRequest.Files.Count > 0)
            {
                var files = new List<string>();

                // interate the files and save on the server
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);

                    files.Add(filePath);
                }

                // return result
                result = Request.CreateResponse(HttpStatusCode.Created, files);
            }
            else
            {
                // return BadRequest (no file(s) available)
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return result;
        }
  • 0
    неперехваченное ссылочное исключение - throwm в коде ниже браузером и остановило исключение. formData.append ("opmlFile", opmlFile.files [0]);

Ещё вопросы

Сообщество Overcoder
Наверх
Меню