【问题标题】:open file from ajax responce in mvc c#在 mvc c# 中从 ajax 响应打开文件
【发布时间】:2017-10-24 13:41:11
【问题描述】:

我想从 Ajax 响应中打开文件。这是代码。这里的 Ajax 调用响应包含 PDF 文件。

我想在浏览器的新标签页中打开文件。这里我使用的是 mvc 框架。

function ViewPDF(key){
$.ajax({
            url: '@Url.Action("OpenDocument", "DocumentApproveUser")',
            type: "POST",
            data: { "key": key},
            async: true,
            cache: false,
            success: function (data, status, xhr) {
                alert(data);
                window.open(data);
                if (xhr.getResponseHeader("Forcefullylogin") == "true") {
                    var url = "/Login/Login";
                    window.location.href = url;
                }
                else {
                }
            },
            error: function (error) {
                $("#divLoading").hide();
                if (error.getResponseHeader("Forcefullylogin") == true") {
                    var url = '@Url.Action("Login", "Login")';
                    window.location.href = url;
                }
                else {
                    alert('Something went wrong in system.Please try again later!or contact to system administrator.');
                }
            }
        });
    }

服务器代码: 下面是我的控制器的代码。此代码将 pdf 文件作为 ajax 响应返回。 我想在我的浏览器中打开该响应。

[HttpPost]
    public ActionResult OpenDocument(string key)
    {
        try
        {
            int Id = 0;
            try
            {
                byte[] data = Convert.FromBase64String(key);
                string decodedString = System.Text.Encoding.UTF8.GetString(data);

                if (!(String.IsNullOrEmpty(decodedString)))
                    Id = Convert.ToInt32(decodedString);
            }
            catch (Exception ex)
            {
                ViewBag.ErrorName = "An error occured while opening document.";
                base.ErrorLogger.Error("***OpenDocument***", ex);
                return null;
            }
            DocumentApproveViewModel vm = new DocumentApproveViewModel();
            vm.DocumentsApprovalModel = DocumentApproveViewModel.GetDocTransactionModelList(_repo.GetAll());
            DocumentApprovalModel lst;

            lst = (from x in vm.DocumentsApprovalModel where x.Id.Equals(Id) select x).FirstOrDefault();
            base.Logger.InfoFormat("User : '{0}' going to access pdf document at {1} ", SessionFactory.CurrentUser.Name, System.DateTime.Now);
            /////////////////////////////////////////////////////////////////////
            ICollection<PasswordManagementViewModel> passwordList = null;
            PasswordManagementViewModel password = null;
            passwordList = PasswordManagementViewModel.GetSystemEncryptionKeyList(_encryption.GetAll());
            password = passwordList.OrderByDescending(x => x.CreatedDateTime).FirstOrDefault();
            string decryptPassword = Base64EncodeDecode.Decrypt(password.EncryptionKey, true);
            /////////////////////////////////////////////////////////////////////
            // Inhariting Logic from PDFSharpUtil Class.
            byte[] PdfFileByte = _docSecurity.OpenPdfFile(lst.File, decryptPassword, SessionFactory.CurrentUser.EncryptionKey, SessionFactory.CurrentUser.Name, lst.DocumentTransactionName, false, SessionFactory.PdfViewCount);

            /// Added logic for adding data into Document History ///
            DocumentHistory objDocumentHistory = new DocumentHistory();
            objDocumentHistory.SentTo = null;
            objDocumentHistory.Timestamp = DateTime.UtcNow;
            objDocumentHistory.ActionPerformedBy = SessionFactory.CurrentUser.Id;
            objDocumentHistory.Action = EDocumentAction.View;
            objDocumentHistory.DocumentId = Id;
            _docHistoryRepo.Add(objDocumentHistory);
            //Increment view count not to ask password from second attempt to open PDF file
            SessionFactory.PdfViewCount++;
            return File(PdfFileByte, "application/pdf");
        }
        catch (Exception ex)
        {
            ViewBag.ErrorName = "An error occured while opening Document";
            base.ErrorLogger.Error("***OpenDocument :: DocumentView***", ex);
        }
        return null;
    }

【问题讨论】:

  • 你也可以分享服务器代码吗?你得到什么错误?
  • OpenDocument 方法返回什么?你为什么要打ajax电话?如果您知道客户端文件的 url,只需使用 window.location.herf=thatUrl;
  • 见上文我也共享了服务器端代码。
  • 您的代码是否询问用户是否要保存文件(或者,根据浏览器设置,自动将其保存到下载文件夹中)?我不认为 ajax 是这样做的正确方法。只需打开一个直接调用 OpenDocument 方法的新窗口(通过 GET,您需要启用该方法),然后它将显示文件,假设用户在其浏览器中安装了 PDF 查看器。

标签: c# jquery ajax model-view-controller


【解决方案1】:

不要尝试使用 ajax 下载文件。只需在新的浏览器选项卡中打开 url。根据您的浏览器设置,它会在选项卡中打开或询问您是否要保存它。

您可以将新网址设置为window.location.href

function ViewPDF(key)
{
   var  url= '@Url.Action("OpenDocument", "DocumentApproveUser")?key='+key,
   window.location.href = url;
}

根据浏览器设置,上述两种方法会询问用户是否希望下载或打开文件,或者只是下载/打开文件。如果您喜欢直接在浏览器中显示文件内容,您可以向浏览器发送文件流。

这是一个简单的例子,它从应用程序根目录下 Contents/Downloads 目录中的磁盘读取 pdf 并返回文件流。

public ActionResult View(int id)
{
    var pathToTheFile=Server.MapPath("~/Content/Downloads/sampleFile.pdf");
    var fileStream = new FileStream(pathToTheFile,
                                        FileMode.Open,
                                        FileAccess.Read
                                    );
    return  new FileStreamResult(fileStream, "application/pdf");           
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2010-12-13
    • 1970-01-01
    • 2021-11-14
    • 2014-02-22
    • 2017-06-12
    相关资源
    最近更新 更多