
Chrome
html<!DOCTYPE html><html><head> <title>Client-side Force Download</title></head><body> Click to Download <script> function forceDownload(url, fileName) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onload = function() { if (xhr.status === 200) { const blob = new Blob([xhr.response]); const downloadLink = document.getElementById('downloadLink'); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = fileName; downloadLink.click(); } }; xhr.send(); } const fileUrl = 'http://example.com/sample.pdf'; const fileName = 'sample.pdf'; forceDownload(fileUrl, fileName); </script></body></html>使用Blob对象和URL.createObjectURL方法实现客户端强制下载:在上面的代码中,我们定义了一个forceDownload函数,它接受文件的URL和文件名作为参数。在函数内部,我们使用XMLHttpRequest对象发送GET请求来获取文件内容。当请求返回成功时(status为200),我们将文件内容封装在Blob对象中,并使用URL.createObjectURL方法生成一个临时的URL。然后,我们将该URL赋值给下载链接的href属性,并设置下载链接的download属性为文件名。最后,我们模拟用户点击下载链接,触发文件的下载。设置Content-Disposition响应头实现客户端强制下载:在服务器端,我们可以设置Content-Disposition响应头来强制浏览器下载文件。具体的方法取决于服务器端的编程语言和框架。下面是一个使用Node.JS和Express框架的例子:Javascriptconst express = require('express');const app = express();app.get('/download', (req, res) => { res.setHeader('Content-Disposition', 'attachment; filename=sample.pdf'); res.sendFile('/path/to/sample.pdf');});app.listen(3000, () => { console.log('Server started on port 3000');});在上述代码中,我们定义了一个/download路由,当用户访问该路由时,服务器会设置Content-Disposition响应头为attachment,并指定文件名为sample.pdf。然后,服务器使用res.sendFile方法将文件发送给客户端,触发文件的下载。通过以上两种方法,我们可以绕过Chrome 65阻止跨源的限制,实现客户端强制下载。根据具体的需求和情况,选择合适的方法来实现文件下载功能。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号