浏览器中,使用文件url来下载文件到本地,并自定义文件名的方法

// 以pdf文件为例
downloadPdfFnc(pdfUrl, pdfName){
      // 构建文件内容
      fetch(pdfUrl)
      .then(response => response.blob())
      .then(blob => {
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `${pdfName}.pdf`; // 设置下载文件的名称
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          URL.revokeObjectURL(url);
          document.body.removeChild(a);
        });
},

在Vue.js中,你可以使用`a`元素配合事件处理程序来实现在线文件下载自定义文件名。以下是一个简单的步骤示例: 1. 首先,获取到需要下载文件URL以及自定义文件名(假设存储在一个变量`customFileName`中)。 ```javascript const downloadLink = 'https://example.com/your-file'; let customFileName = 'custom_file_name.txt'; ``` 2. 使用`@click`或者其他事件监听器创建一个点击事件,当用户点击时触发下载操作: ```html <a id="download-link" @click.prevent="downloadFile">下载</a> <script> export default { methods: { downloadFile() { const element = document.getElementById('download-link'); element.href = downloadLink; element.download = customFileName; // 设置下载文件名 }, }, }; </script> ``` 3. 如果文件内容是从服务器动态获取的,你需要先将文件内容转换成Blob对象,然后设置`href`属性。这通常涉及到HTTP请求,可以借助axios或其他库来完成。例如: ```javascript methods: { async downloadFile() { const response = await axios.get(downloadLink); const blob = new Blob([response.data], { type: 'application/octet-stream' }); const url = window.URL.createObjectURL(blob); const element = document.getElementById('download-link'); element.href = url; element.download = customFileName; }, } ``` 请注意,实际应用中可能还需要处理浏览器兼容性和错误情况。上述代码提供了一个基础框架,你可能需要根据具体需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值