繁体   English   中英

在MVC中使用Javascript将Json对象和文件发送到控制器

[英]Send Json object and file to controller with Javascript in MVC

我有一个像Json对象:

  var appversion = { "Id": "", "Version": "", "HelpSystemId": "", "Content": "", "FileName": "", "IsLatest": "", "LastModify": "", "AppVersionChangsets": [] };
        appversion.Id = $("#Id").val();
        appversion.Version = $("#Version").val();
        appversion.HelpSystemId = $("#HelpSystemId").val();
        appversion.IsLatest = $("#IsLatest").val();
        appversion.LastModify = $("#LastModify").val();

以及我以这种方式获取的文件:

<div class="form-group">
        @Html.MyLabelFor(model => model.Content, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" id="_file" name="_file" />
            <button onclick="abortRead();">Cancel read</button>
            <div id="progress_bar"><div class="percent">0%</div></div>
        </div>
    </div>

然后将其发送给我的控制器:

 $.ajax({
          url: '/AppVersion/Create2',
          data: JSON.stringify(appversion),
          type: 'POST',
          contentType: 'application/json;',
          dataType: 'json',
         success: function (result) {
               if (result.Success == "1") {
                    window.location.href = "/AppVersion/index";
               }
               else {
                   alert(result.ex);
               }
           }});

控制器是:

    [HttpPost]
    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult Create2(AppVersion appversion)
    {
    //Some Code
    }

我的问题是我无法访问控制器中的文件。 我只是得到我的json对象。如何将带有Json对象的文件发送到Controller?

  if (Request.Files["file"].ContentLength > 0)
                {
                    Stream str = Request.Files["file"].InputStream;
                    byte[] data = new byte[str.Length];
                    str.Read(data, 0, System.Convert.ToInt32(str.Length));
                }

有一个名为“ ajaxfileupload”的Jquery插件,也许您可​​以使用它。 网址为“ http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ ”。

暂无
暂无

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

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