300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > ASP.NET解决PDF.js跨域访问问题

ASP.NET解决PDF.js跨域访问问题

时间:2023-11-03 15:22:04

相关推荐

ASP.NET解决PDF.js跨域访问问题

PDF.js在访问pdf文件的时候,有时候会涉及到跨域问题,介绍一种.NET和PDF.js配合使用的方法。

前端代码:

<script type="text/javascript">var PDFData = "";$.ajax({type: "get",crossDomain: true,async: false, // false是不采用异步的方式mimeType: 'text/plain;charset=x-user-defined',//这里是后台方法,根据实际情况编写自己的参数,主要是返回文件流url: "http://localhost:61582/Seal/DownLoad?Name=1107&ProjectId=1&SignCount=2", success: function (data) {PDFData = data; // data是byte[]数组}});var rawLength = PDFData.length;// 转换成pdf.js能直接解析的Uint8Array类型,见pdf.js-4068var array = new Uint8Array(new ArrayBuffer(rawLength));for (var i = 0; i < rawLength; i++) {array[i] = PDFData.charCodeAt(i) & 0xff;}var pdf_url = array;// var url = 'default.pdf';var pdfh5 = new Pdfh5('.pdfjs', {pdfurl: pdf_url});//监听当前加载的pdf页数,currentPageDom当前加载的pdf的dom,currentNum当前加载的pdf页数,pdfh5.on("renderPages",function(currentPageDom){console.log(this.currentNum)console.log(pdfh5.currentNum)})</script>

注意前端代码那里的URL,根据实际情况编写所需参数,主要是返回文件流,就可以。

后端代码:

public void DownLoad(string Name, int ProjectId,int SignCount){Response.ContentType = "application/x-zip-compressed";Response.AddHeader("Content-Disposition", "attachment;filename=" + Name + ".pdf");string filename = Server.MapPath(EM.getPdfpath((EM.ProjectFold)ProjectId) + (SignCount==1? "signone\\" : "signtwo\\") + Name + ".pdf");Response.TransmitFile(filename);}

filename根据项目实际情况,获取到文件所在路径地址,再使用上边的代码,这样就可以了。

注意webconfig中需要添加一个设置,在system.webServer中添加如下内容:

<httpProtocol><customHeaders><add name="Access-Control-Allow-Origin" value="*" /><add name="Access-Control-Allow-Headers" value="*" /><add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /></customHeaders></httpProtocol>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。