简体   繁体   English

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

[英]send file through ajax to another action mvc5 c#

I'm trying to send a file via ajax to an action in a controller, i know there is a lot of existing questions about this topic but none of them have solved my problem.我正在尝试通过 ajax 将文件发送到控制器中的操作,我知道关于这个主题有很多现有问题,但没有一个解决了我的问题。

I have a view where the users will upload a file and i'm trying to get that file in the controller but I always get 0 as result of Request.Files.Count();我有一个视图,用户将上传一个文件,我试图在控制器中获取该文件,但由于 Request.Files.Count(); 我总是得到 0;

The action called in the ajax is different from the actual view. ajax 中调用的动作与实际视图不同。

I'm using MVC5 with ASP.NET and C#我在 ASP.NET 和 C# 中使用 MVC5

Hope you can help me.希望您能够帮助我。 Thanks!.谢谢!。

My view:我的看法:

`@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: 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>

Controller:控制器:

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 });
}

UPDATE:更新:

I've solved it.我已经解决了。

This line was wrong:这一行是错误的:

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

Should be like this:应该是这样的:

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

i generate code for your problem and hopefully it will very helpful for you.我为您的问题生成代码,希望它对您很有帮助。

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");
        }
    }

View看法

<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>

Jquery With Ajax Request带有 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>
  }

if you need code then please visit my github repostory and find the project如果您需要代码,请访问我的 github 仓库并找到该项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM