如何通过MVC4上传文件,并得到JSON响应 [英] How to upload file via MVC4 and get json response

查看:117
本文介绍了如何通过MVC4上传文件,并得到JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to upload file using MVC4 syntax

@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我有回报重定向页面。

This one seen to be not work because all time time submit button is clicked, it will fall to this controller and try to redirect page with json I have return.

所以,有无论如何要上传的文件,并得到JSON响应,我需要使用此JSON响应呈现内容在本页面

So, there is anyway to upload file and get json response, I need to use this json response to render content in this page

推荐答案

您需要阿贾克斯后,而不是Html.BeginForm()。
因此,使用的jQuery插件形成并<一个href=\"http://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor\">Ajax.BeginForm()这使得任务那么容易。
下面是步骤。

You need ajax post instead of Html.BeginForm(). So, use jquery forms plugin and Ajax.BeginForm() which makes the task so easy. Here are the steps.

包含库

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

这篇关于如何通过MVC4上传文件,并得到JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆