通过ajax发送文件到另一个动作mvc5 c#

时间:2019-03-01 18:09:16

标签: c# ajax asp.net-mvc-5

我正在尝试通过ajax将文件发送到控制器中的某个动作,我知道有关此主题的现有问题很多,但是没有一个解决了我的问题。

我有一个视图,用户将在其中上传文件,我试图在控制器中获取该文件,但是由于Request.Files.Count();我总是得到0。

ajax中调用的操作与实际视图不同。

我正在将MVC5与ASP.NET和C#一起使用

希望您能帮助我。谢谢!。

我的观点:

`@using (Html.BeginForm("editProject", "Projects", new { area = "admin" }, 
FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = 
"multipart/form-data" }))
{
@Html.AntiForgeryToken()
<input type="file" id="inpFile" name="attachment" multiple>
}`

Javascript:

<script type="text/javascript">
    var res = document.getElementById("inpFile");
    res.addEventListener("change", function () {
    files = document.getElementById("inpFile").files;
    data = new FormData();
    data.append(files[0].name, files);
    $.ajax({
        url: "@Url.Action("SaveFile", "Projects",new { area = "admin" })",
        type: "POST",
        datatype: "json",
        data: data,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log(data.UploadedFileCount + ' file(s) uploaded 
    successfully');
                }
            });
    });
    </script>

控制器:

public JsonResult SaveFile()
{           
for (int i = 0; i < Request.Files.Count; i++)
{
    var file = Request.Files[i];
    // saving file...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}

更新:

我已经解决了。

此行是错误的:

data.append(files[0].name, files);

应该是这样的:

data.append(files[0].name, files[0]);

1 个答案:

答案 0 :(得分:-1)

我会为您的问题生成代码,希望它将对您有所帮助。

Contoller

 public ActionResult Index()
    {
        return View();
    }
    public ActionResult Upload()
    {
        if (Request.Files["ChequeFile"].ContentLength > 0)
        {
            String path = "~/Content/";
            var fileName = Path.GetFileName(Request.Files["ChequeFile"].FileName);
            Random rnd = new Random();
            int rndnumber = rnd.Next(1, 9999999);
            var filepath = Path.Combine(path, rndnumber + "" + fileName);
            if (System.IO.File.Exists(filepath))
            { System.IO.File.Delete(filepath); }
            Request.Files["ChequeFile"].SaveAs(Server.MapPath(filepath));

            return Json("File Successfully Upload via ajax.");
        }
        else
        {
            return Json("File Must Be Required");
        }
    }

查看

<div class="jumbotron">
<h1>Upload File via Ajax in MVC5 C#</h1>
    <div id="notification"></div>
    <input type="file" required="required" id="ChequeFile" name="ChequeFile" />
    <br />

    <button type="submit" id="uploadss" class="btn btn-primary">Upload File</button>

带有Ajax请求的jQuery

@section scripts{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $(document).on('click', "#uploadss", function () {
        debugger;
        var fdata = new FormData();
        $('input[name="ChequeFile"]').each(function (a, b) {
            var fileInput = $('input[name="ChequeFile"]')[a];
            if (fileInput.files.length > 0) {
                var file = fileInput.files[0];
                fdata.append("ChequeFile", file);
            }
        });
        $.ajax({
            //cache: false,
            //async: true,
            type: "POST",
            url: "/Home/Upload",
            data: fdata,
            contentType: false,
            processData: false,
            success: function (data) {
                //debugger;
                $("#notification").html('');
                $("#notification").html(data);
            },
            error: function (data) {
                $("#notification").html('');
                $("#notification").html(data);
            }
        });
    })
</script>
  }

如果您需要代码,请visit我的github repostory并找到项目