【问题标题】:How to upload file via MVC4 and get json response如何通过 MVC4 上传文件并获取 json 响应
【发布时间】:2014-04-11 17:12:22
【问题描述】:

我尝试使用 MVC4 语法上传文件

@using (Html.BeginForm("ImportCsv","ASPolicy", FormMethod.Post, new {enctype = "multipart/form-data"}))
            {
                <input type="file" name="file" style="display: none"/>
                <input type="text" name="cid" value="'@ViewData["cid"]'" style="display: none"/>
                <input type="submit" value="upload" style="display: none"/>
            }

我的控制器看起来像

public JsonResult ImportCsv(HttpPostedFileBase file, String cid)
    {

        IPRestriction ipRestriction = new IPRestriction();
        List<string> ipList = new List<string>();

        using (BinaryReader b = new BinaryReader(file.InputStream))
        {
            byte[] binData = b.ReadBytes(Convert.ToInt32(file.InputStream.Length));
            string result = System.Text.Encoding.Unicode.GetString(binData);

            TextReader textReader = new StringReader(result);
            CsvReader csv = new CsvReader(textReader, new CsvConfiguration() {Delimiter = "\t"} );

            while (csv.Read())
            {
                string accountNumber = csv.GetField(0);
                string ip = csv.GetField(1);
                ipRestriction.accountNumber = accountNumber;
                ipList.Add(ip);
            }

            ipRestriction.ipAllowList = ipList.ToArray();
        }

        String jsonStr = JsonConvert.SerializeObject(ipRestriction);
        return Json(jsonStr, JsonRequestBehavior.AllowGet);
    }

这个看起来不起作用,因为所有时间提交按钮都被点击,它会落到这个控制器上,并尝试用我返回的 json 重定向页面。

所以,无论如何上传文件并获取json响应,我需要使用这个json响应来渲染这个页面中的内容

【问题讨论】:

标签: html ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

您需要 ajax post 而不是 Html.BeginForm()。 因此,请使用jquery forms pluginAjax.BeginForm(),这会使任务变得如此简单。 步骤如下。

包括库

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

查看

//Returned Json value will be here.
<div id="result"></div>

@using (Ajax.BeginForm("ImportCsv", "ASPolicy", new AjaxOptions() { HttpMethod = "POST" , UpdateTargetId = "result" }, new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files"><br>
    <input type="submit" value="Upload File to Server">
}

控制器

public JsonResult ImportCsv(IEnumerable<HttpPostedFileBase> files, String cid)
{
    if (files != null)
    {
        foreach (var file in files)
        {
            // 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);
                file.SaveAs(path); //upload for example
            }
        }
    }

    //String jsonStr = JsonConvert.SerializeObject(ipRestriction);
    return Json(jsonStr, JsonRequestBehavior.AllowGet); //Now return Json as you need.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多