【问题标题】:the pdf file is not displayed from byte array in the iframepdf文件不从iframe中的字节数组显示
【发布时间】:2017-10-03 10:29:24
【问题描述】:

我正在开发 MVC 5 Visual Studio 15。我的应用程序需要在 iframe 中显示字节数组中的 PDF 文件。为此,我使用以下 javascript。但这不起作用。任何人请告诉我我正在做的错误。

 $(document).ready(function () {
        $.ajax({
            async: false,
            cache: false,
            type: "POST",
            url: "@(Url.RouteUrl("GetAnyRespons"))",
            responseType: 'arraybyte',
            success: function (JsonCP) {
                var data = JsonCP.responseModel.response.ResponseImage;
                var file = new Blob([data], { type: 'application/pdf' });
                var fileURL = URL.createObjectURL(file);
                var iframe = document.createElement('iframe');
                iframe.className = 'responseframe';
                iframe.src = fileURL;
                $('#response').append(iframe);
                alert('response Loaded.');
            },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError + ' Failed to retrieve response.');
         }
    });
 }); 

 <div id="container">
    <div  id="response">

    </div>
    <div id="marks"></div>
</div>

带有一些其他数据的字节数组被控制器转换成JSON数据后传递给客户端。

 [System.Web.Http.HttpPost]
    public ActionResult GetAnyRespons()
    {
        DownloadResponseModel rm = new DownloadResponseModel();
        JsonResult jsonResult = Json(rm, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;
    }

字节数组通过以下函数从数据库中读取。

 public int getFStreamResponse(System.Guid guid)
    {
        SqlConnection sqlConnection = new SqlConnection();
        sqlConnection.ConnectionString = "Data    
        Source=HOME\\MSQLEXPRESS2016;Initial Catalog=Evaluation;Integrated  
        Security=True";
        sqlConnection.Open();
        SqlCommand sqlCommand = new SqlCommand();
        sqlCommand.Connection = sqlConnection;
        sqlCommand.Transaction = sqlConnection.BeginTransaction();
        sqlCommand.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT
        ()";
        sqlCommand.CommandType = System.Data.CommandType.Text;
        byte[] transactionContext = (byte[]) sqlCommand.ExecuteScalar();
        SqlParameter parameter;
        sqlCommand.CommandText = "SELECT [AllPagesAnotted], 
        [MarkedPercentage],[Mark], [RegdNo],[QuestionPaperId],[Assigned],  
        [Evaluated],[ResponseImage].PathName() AS FilePath FROM Responses  
        WHERE [ResponseId] = @Id";
        sqlCommand.CommandType = System.Data.CommandType.Text;
        parameter = new System.Data.SqlClient.SqlParameter("@Id", 
        System.Data.SqlDbType.UniqueIdentifier);
        parameter.Value = guid;
        sqlCommand.Parameters.Add(parameter);
        SqlDataReader reader = sqlCommand.ExecuteReader();
        reader.Read();
        this.response.AllPagesAnotted =(bool)reader["AllPagesAnotted"];
        this.response.MarkedPercentage= (int)reader["MarkedPercentage"];
        this.response.Mark= (int)reader["Mark"];
        this.response.RegdNo = (string)reader["RegdNo"];
        this.response.QuestionPaperId = (int)reader["QuestionPaperId"];
        this.response.Assigned = (bool)reader["Assigned"];
        this.response.Evaluated = (bool)reader["Evaluated"];
        this.response.ResponseId = guid;
        string filePathInServer = (string)reader["FilePath"];
        reader.Close();
        SqlFileStream sqlFileStream = new System.Data.SqlTypes.SqlFileStream
        (filePathInServer, (byte[])transactionContext, 
        System.IO.FileAccess.Read);
        this.response.ResponseImage = new byte[sqlFileStream.Length];
        sqlFileStream.Seek(0L, System.IO.SeekOrigin.Begin);
        int byteAmount = sqlFileStream.Read        
        (this.response.ResponseImage,  0,  (int)sqlFileStream.Length);
        sqlFileStream.Close();
        sqlCommand.Transaction.Commit();
        return byteAmount;
    }

【问题讨论】:

    标签: javascript c# angularjs


    【解决方案1】:

    您的 AJAX 调用正在执行 HTTP GET 请求,并且您的 JsonResult GetAnyRespons() 被 HTTP POST 修饰。

    【讨论】:

    • 我已经更改了 get to post 的 ajax 调用,但仍然无法正常工作。pdf 文件未显示。
    【解决方案2】:

    如果我们使用jpg代替pdf,问题就可以解决。以下代码显示多页的jpg。

    $(document).ready(function (JsonCP) {
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                dataType: "json",
                url: "@(Url.RouteUrl("GetAnyRespons"))",
                success: function (JsonCP) {
                    base64String =       
     base64js.fromByteArray(JsonCP.responseModel.response.ResponseImage);
                    imgid = 'but1';
                    span = document.createElement('span');
                    var but = ($('<input>').attr('type', "image")
                        .attr('id', imgid)
                        .attr('src', "data:image/jpg;base64," + base64String)
                        .attr('width','900px')
                        ).appendTo(span);
                    $('#response1').append(span);
                },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(thrownError + ' Failed to retrieve response.');
             }
        });
     });
    
    </script>
    
    </head
    <body>
        <div class="outerdiv" >
            <div id="response1" ></div>
        </div>
    </body>
    </html>
    
    .outerdiv{
        overflow-y: scroll;
        overflow-x:hidden;
        height: 1100px;
        width:900px;
     }  
    

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 2021-11-01
      • 2012-03-25
      • 2018-11-10
      • 2013-03-03
      • 2021-04-11
      相关资源
      最近更新 更多