要实现多张图片的下载功能,可以使用JavaScript中的<a>
标签的download
属性,结合Blob
对象来创建可下载的文件。以下是一个简单的示例代码,展示了如何实现这一功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download Multiple Images</title>
</head>
<body>
<input type="file" id="fileInput" multiple>
<button onclick="downloadImages()">Download Selected Images</button>
<script>
function downloadImages() {
const fileInput = document.getElementById('fileInput');
const files = fileInput.files;
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type.startsWith('image/')) {
const url = URL.createObjectURL(file);
const a = document.createElement('a');
a.href = url;
a.download = file.name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
}
}
</script>
</body>
</html>
download
属性。可以通过特性检测来提供回退方案。对于跨浏览器兼容性问题,可以添加如下检测代码:
if ('download' in document.createElement('a')) {
// 支持download属性
} else {
// 不支持download属性,提供其他下载方式
}
通过这种方式,可以确保在不支持download
属性的浏览器中提供替代的用户体验,比如提示用户右键保存图片。
领取专属 10元无门槛券
手把手带您无忧上云