Excel文件未保存在用户的PC中

时间:2015-04-01 07:16:07

标签: asp.net-mvc excel

我尝试将excel文件从服务器下载到用户的PC。我有来自互联网的以下代码。我稍微修改了代码....

但是当我运行代码时,没有任何反应。保存对话框没有弹出。我真正想要的是通过弹出一个保存对话框,来自服务器的excel文件将保存在用户的PC中。

请帮助!!!

public void DownloadFile(string url)
{
    string path = Server.MapPath("~/Images/0ca66926-6977-43d3-9c97-f84a43f6ce5d.xls");
    var file = new FileInfo(path);
    string Outgoingfile = "FileName.xlsx";
    if (file.Exists)
    {
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.WriteFile(file.FullName);
        Response.Flush();
        Response.Close();

    }
    else
    {
        Response.Write("This file does not exist.");
    }
} 

$.ajax({
    url: '@Url.Action("DownloadFile", "Home")',
    type: 'POST',
    contentType: "application/json",
    data: JSON.stringify({ url: urlLink}),
    success: function(res) {

    },
    error: (function() {
        alert("Error to retrieve selected report");
    })
});

1 个答案:

答案 0 :(得分:0)

由于您正在寻找有效的下载文件代码,我正在分享我们使用的内容。

我们有两个调用过程来下载代码。第一次调用将文件准备好并保存在服务器上。下面显示的第二个调用读取文件内容并返回文件对象。

<强> Controller.cs

    [HttpGet]
    public ActionResult DownloadStream(string fileName, int searchId)
    {
        var tempStore = _searchService.GetTempStore(searchId);
        var bytes = tempStore.DataAsBlob;
        if (bytes != null)
        {
            var stream = new MemoryStream(bytes);
            _searchService.DeleteTempStore(searchId);
            return File(stream, "application/vnd.ms-excel", fileName);
        }

        _logger.Log("Export/DownloadStream request failed", LogCategory.Error);
        return Json("Failed");
    }

<强> View.cshtml

以下行调用服务器上的DownloadStream方法,服务器发送一个在用户计算机上保存的文件对象。

  

window.location ='/ Export / DownloadStream?fileName ='+   结果+ “&安培; searchId =” + searchId;

    function ExportData(exportType, exportFormat) {

        var searchId = document.getElementById('hfSelectedDriverId').value;
        var model = { searchId: searchId, exportType: exportType, exportFormat: exportFormat };

        $.ajax({
            url: '@Url.Action("ExportDriverFile", "Export")',
            contentType: 'application/json; charset=utf-8',
            type: 'POST',
            dataType: 'html',
            data: JSON.stringify(model)
        })
            .success(function (result) {
                result = result.toString().replace(/"/gi, "");
                if (result == "" || result == "failed")
                {
                    alert("File download failed. Please try again!");
                }
                else
                {
                    window.location = '/Export/DownloadStream?fileName=' + result+"&searchId="+searchId;
                }
            })
        .error(function (xhr, status) {
            //alert(status);
        });
    }