原生JS请求并直接下载PDF文件,后台返回文件流

 html代码

function dowmloadFile(id) {
	var filename = "文件";
	$.ajax({
		url: "http://localhost:8080/interface/getFile",
		type: "POST",
		mimeType: "text/plain;charset=x-user-defined",
		data: {
			id: id
		},
		responseType: 'blob',
		success: function (res) {
			var rawLength = res.length;
			var array = new Uint8Array(new ArrayBuffer(rawLength));
			for (let index = 0; index < rawLength; index++) {
				array[index] = res.charCodeAt(index) & 0xff;
			}

			var blob = new Blob([array], {type: "application/pdf;charset-UTF-8"});
			if (typeof window.navigator.msSaveBlob !== 'undefined') {
				window.navigator.msSaveBlob(blob, filename);
			}
			else {
				var blobURL = (window.URL && window.URL.createObjectURL) ? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob);
				var tempLink = document.createElement('a');
				tempLink.style.display = 'none';
				tempLink.href = blobURL;
				tempLink.setAttribute('download', filename);

				if (typeof tempLink.download === 'undefined') {
					tempLink.setAttribute('target', '_blank');
				}

				document.body.appendChild(tempLink);
				tempLink.click();

				setTimeout(function () {
					document.body.removeChild(tempLink);
					window.URL.revokeObjectURL(blobURL);
				}, 200)
			}
		}
	})
}

 java代码

@RequestMapping(value = "/getFile", method = RequestMethod.POST)
@ResponseBody
public void getFile(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) {
    try {
    ServletOutputStream out;
    Detail article = interfaceService.getArticleById(id);
    String url = article.getAccessory();
    String name = article.getName();
    URL url1 = new URL(Config.url + url);
    URLConnection conn = url1.openConnection();
    InputStream in = conn.getInputStream();
    String afterName = url.substring(url.lastIndexOf(".") + 1);
    response.setContentType(conn.getContentType());
    response.setHeader("Content-Disposition", "attachment; filename=" +         URLEncoder.encode(name + "." + afterName, "UTF-8"));
    response.setCharacterEncoding("UTF-8");
    int len;
    byte[] buffer = new byte[1024 * 10];
    out = response.getOutputStream();
    while ((len = in.read(buffer)) > 0) {
          out.write(buffer, 0, len);
    }
    out.flush();
    out.close();
    in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 response中,filename还是乱码,不过无所谓了,实现了下载就行。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在原生JS中引入pdf.js并显示本地PDF文件,你可以按照以下步骤操作: 1. 首先,在你的HTML文件中引入pdf.jspdf.worker.js文件,例如: ```html <script src="pdf.js"></script> <script src="pdf.worker.js"></script> ``` 请确保这两个文件在同一个目录下,并且文件名正确。 2. 创建一个用于显示PDF文件的`<canvas>`元素和一个按钮,例如: ```html <canvas id="pdf-canvas"></canvas> <button id="pdf-btn">打开PDF文件</button> ``` 请注意,我们将为`<canvas>`元素指定一个ID,以便稍后在JavaScript中引用它。 3. 在JavaScript中,我们需要编写一个函数来加载并显示PDF文件。例如: ```javascript function showPDF(pdf_url) { // 获取<canvas>元素 var canvas = document.getElementById('pdf-canvas'); // 获取渲染上下文 var ctx = canvas.getContext('2d'); // 加载PDF文件 PDFJS.getDocument(pdf_url).then(function(pdf) { // 获取第一页 pdf.getPage(1).then(function(page) { // 计算缩放比例 var viewport = page.getViewport(canvas.width / page.getViewport(1.0).width); // 渲染页面 page.render({ canvasContext: ctx, viewport: viewport }); }); }); } // 为按钮添加点击事件,弹出文件选择框 document.getElementById('pdf-btn').addEventListener('click', function() { var input = document.createElement('input'); input.type = 'file'; input.onchange = function() { var file = input.files[0]; var reader = new FileReader(); reader.onload = function(event) { var url = event.target.result; showPDF(url); }; reader.readAsDataURL(file); }; input.click(); }); ``` 在这个函数中,我们使用PDFJS库的`getDocument()`函数来加载PDF文件,然后使用`getPage()`函数获取文件的第一页。我们计算缩放比例,渲染页面并将其显示在`<canvas>`元素中。最后,我们为按钮添加一个点击事件,弹出文件选择框,让用户选择要打开的PDF文件。 请注意,我们使用`FileReader`对象来读取本地文件并将其转换为Data URL,以便我们可以将其传递给`showPDF()`函数。 希望这可以帮助你实现在原生JS中引入pdf.js并显示本地PDF文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独来独往V5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值