JSON结果下载zip文件不起作用

时间:2018-01-15 13:47:16

标签: c# json asp.net-mvc download zip

以下代码在我的本地开发机器中完美运行,但在托管机器中没有。

托管计算机中的行为是在URL地址中显示此行浏览器,而不是下载文件:

http://www.dcsyslogin.com/Index/Download?fileGuid=3797ed2d-4239-48b9-b228-165a890c89f5&mimeType=application/zip,%20application/octet-stream&filename=OT_19.zip

我在firefox和chrome中测试了这个结果。

在我的本地机器上工作正常下载de ZIP dile。

有什么建议可以吗?

由于

在视图中:

<a href="javascript: RunReportTodos('@Url.Action("DescargarFotos","Index", new { Id = Model.Id })')" , class="btn btn-primary" onclick="return confirm('Está seguro(a) de bajar archivos la OT');">Bajar archivos y fotos</a>

完整视图:

@model DCSystem.Areas.VSX.Models.AdminOTModel
@{
    ViewBag.Title = "VSX - Administrar OT";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("AdminOT", "Index", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="panel panel-primary">
        <div class="panel-heading">
            @ViewBag.Title
        </div>
        <div class="form-horizontal">
            @Html.HiddenFor(x => x.Estado)
            @Html.Label("Seleccione OT :", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(x =>
                  x.Id,
(IEnumerable<SelectListItem>)ViewBag.selectItemsOts,
new
{
    @class = "form-control selectpickerOT",
    data_live_search = "true",
    title = "Vacío",
    onchange = "this.form.submit();",
})
                @Html.ValidationMessageFor(model => model.Id)
            </div>
        </div>
        @if (Model.Id > 0)
        {
            <table class="table">
                <tr>
                    <td colspan="2" align="left">
                        @*@Html.ActionLink("Procesar formularios", "Generar", new { id = Model.Id }, new { @class = "btn btn-primary", @onclick = "return confirm('Esta seguro(a) de generar OT') && DisplayProgressMessage();" })*@
                        <a href="javascript: RunReportTodos('@Url.Action("DescargarFotos","Index", new { Id = Model.Id })')" , class="btn btn-primary" onclick="return confirm('Está seguro(a) de bajar archivos la OT');">Bajar archivos y fotos</a>

                         @if (Model.Estado == DCSystem.Areas.VSX.Models.EstadosOT.ARCHIVADA)
                        {
                            @Html.ActionLink("Des Archivar", "Archivar", new { id = Model.Id }, new { @class = "btn btn-primary", @onclick = "return confirm('Esta seguro(a) de Desarchivar OT');" })
                         }
                         else
                         {
                             if (Model.Estado == DCSystem.Areas.VSX.Models.EstadosOT.ENPROCESO)
                             {
                                @Html.ActionLink("Publicar", "Publicar", new { id = Model.Id }, new { @class = "btn btn-primary", @onclick = "return confirm('Esta seguro(a) de publicar OT');" })
                                @Html.ActionLink("Archivar", "Archivar", new { id = Model.Id }, new { @class = "btn btn-primary", @onclick = "return confirm('Esta seguro(a) de archivar OT');" })
                                @Html.ActionLink("Eliminar", "Eliminar", new { id = Model.Id }, new { @class = "btn btn-danger", @onclick = "return confirm('Esta seguro(a) de eliminar OT');" })
                             }
                             if (Model.Estado == DCSystem.Areas.VSX.Models.EstadosOT.MINISTERIO)
                             {
                                @Html.ActionLink("Activar", "Publicar", new { id = Model.Id }, new { @class = "btn btn-primary", @onclick = "return confirm('Esta seguro(a) de archivar OT');" })
                                @Html.ActionLink("Archivar", "Archivar", new { id = Model.Id }, new { @class = "btn btn-primary", @onclick = "return confirm('Esta seguro(a) de archivar OT');" })
                             }
                         }


                    </td>
                </tr>
                <tr>
                    <td>
                        <input id="NombreArchivo" type="file" name="UploadedFile" class="btn btn-primary" accept=".zip" />
                    </td>
                    <td>
                        <input type="submit" onclick="return DisplayProgressMessage();" name="Submit" value="Subir archivo" class="btn btn-primary" />
                    </td>
                </tr>
            </table>
        }
        <div>

        </div>
    </div>
}
<script>
    $('.selectpickerOT').selectpicker({
        liveSearch: true
    });
</script>
<script type="text/javascript">
    function RunReportTodos(reportUrl) {
        setTimeout(function () {
            $("body").addClass("submit-progress-bg");
        }, 1);

        setTimeout(function () {
            $(".submit-progress").removeClass("hidden");
        }, 1);

        $.ajax({
            cache: false,
            url: reportUrl,
            type: "POST",
            success: function (response) {
                window.location = "/Index/Download?fileGuid=" + response.FileGuid +
                   "&mimeType=" + response.MimeType + "&filename=" + response.FileName;
                setTimeout(function () {
                    $(".submit-progress").addClass("hidden");
                }, 1);
                setTimeout(function () {
                    $("body").removeClass("submit-progress-bg");
                }, 1);
            }
        });

    }
</script>

在控制器中:

public ActionResult DescargarFotos(int id)
{
    var t = GenerarAsync(id);
    VSX_OT OT = db.VSX_OTs.Find(id);
    string OTDir = System.Web.Hosting.HostingEnvironment.MapPath("\\UserFiles\\VSX");
    OTDir += "\\OT_" + OT.OT.ToString();
    OTDir += "\\FOTOS\\";

    string codunicotemporal = Guid.NewGuid() + "_" + DateTime.UtcNow.ToString("yyyyMMddhhmmss");

    string zipTemporal = System.Web.HttpContext.Current.Server.MapPath("//UserFiles//" + codunicotemporal) + ".zip";

    ZipFile.CreateFromDirectory(OTDir, zipTemporal);

    var bytes = System.IO.File.ReadAllBytes(zipTemporal);

    System.IO.File.Delete(zipTemporal);

    if (System.IO.Directory.Exists(OTDir))
    {
        System.IO.Directory.Delete(OTDir, true);
    }

    using (var stream = new MemoryStream(bytes))
    {
        string handle = Guid.NewGuid().ToString();
        Session[handle] = stream.ToArray();
        return new JsonResult()
        {
            Data = new
            {
                FileGuid = handle,
                MimeType = "application/zip, application/octet-stream",
                FileName = "OT_" + OT.OT.ToString() + ".zip"
            }
        };
    }


}

public ActionResult Download(string fileGuid, string mimeType, string filename)
{
    if (Session[fileGuid] != null)
    {
        byte[] data = Session[fileGuid] as byte[];
        Session.Remove(fileGuid);  // Cleanup session data
        return File(data, mimeType, filename);
    }
    else
    {
        // Log the error if you want
        return new EmptyResult();
    }
}

1 个答案:

答案 0 :(得分:0)

为了解决这个问题,我添加了MaxJsonLength = Int32.MaxValue:

return new JsonResult()
                {
                    Data = new
                    {
                        FileGuid = handle,
                        MimeType = System.Net.Mime.MediaTypeNames.Application.Zip,
                        FileName = "OT_" + OT.OT.ToString() + ".zip",
                        MaxJsonLength = Int32.MaxValue
                    }
                };

并更改流程以获得更小的zip文件:从90000 Kb到10000 kb。