js下载文件修改文件名
时间: 2023-08-22 15:06:37 浏览: 72
你可以使用 JavaScript 创建一个带有下载文件名的链接,并单击该链接来下载文件。以下是一个例子:
```javascript
function downloadFile(filename, content) {
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Example usage:
const fileContent = 'This is the content of my file';
const filename = 'myfile.txt';
downloadFile(filename, fileContent);
```
在这个例子中,我们定义了一个 `downloadFile` 函数,在该函数中创建一个带有指定文件名和内容的下载链接。
在这个函数中,我们使用了 `createElement` 方法创建一个新的 `a` 元素,并将 `href` 属性设置为一个 `data` URL,该 URL 包含文件内容和编码类型。我们还将 `download` 属性设置为文件名,以便浏览器知道下载文件应该使用的文件名。最后,我们将该元素附加到文档的 `body` 中,单击该元素以触发下载,然后将其从文档中删除。
你可以将 `filename` 和 `content` 参数替换为你自己的值,并根据需要调整其他属性和样式。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)