js通过url下载 浏览器不弹下载框,代码中指定下载目录
时间: 2024-04-18 18:34:09 浏览: 8
你可以使用 JavaScript 中的 `XMLHttpRequest` 对象来实现通过 URL 下载文件,同时也可以指定下载目录。以下是一个示例代码:
```javascript
function downloadFile(url, directory) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (xhr.status === 200) {
var blob = xhr.response;
var fileName = getFileNameFromUrl(url);
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = directory + fileName;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
};
xhr.send();
}
function getFileNameFromUrl(url) {
var index = url.lastIndexOf('/') + 1;
return url.substr(index);
}
// 使用示例:
var fileUrl = 'http://example.com/file.txt';
var downloadDir = 'downloads/';
downloadFile(fileUrl, downloadDir);
```
上述代码通过创建一个隐藏的 `<a>` 标签,并设置 `download` 属性来指定下载目录和文件名。然后,使用 `a.click()` 方法来触发下载操作。请注意,由于浏览器的安全策略限制,该方法只能在用户触发的事件处理程序中调用,例如点击按钮。
请确保在使用此代码时,遵守相关的法律法规并尊重目标服务器的使用规则。