在使用el-upload时,点击文件预览列表下载文件的方法:
这是文件上传的组件,通过绑定:file-list属性来获取文件列表,:on-preview 则绑定文件预览时的事件。
<el-upload
v-model:file-list="fileList"
accept=".txt"
action=""
disabled
:on-preview="handlePreviewDownloadFile"
multiple/>
通过将文件的内容转化为blob对象从而防止下载的文件出现乱码。然后使用`document.createElement('a');` 这个来创建下载节点。并设置a节点的各个属性。然后将连接加载到dom中。并在下载成功后删除a元素。
const handlePreviewDownloadFile = async (file) => {
if (file.url != null && file.url !== '') {
let downloadUrl = file.url;
try {
const response = await fetch(downloadUrl); // 获取文件内容
if (!response.ok) {
throw new Error('文件下载失败');
}
const blob = await response.blob(); // 将文件内容转换为 Blob 对象
const link = document.createElement('a');
link.href = URL.createObjectURL(blob); // 创建一个 URL 对象
link.download = file.name; // 指定下载的文件名
document.body.appendChild(link); // 将链接添加到 DOM 中
link.click(); // 触发下载
document.body.removeChild(link); // 下载后移除 <a> 元素
} catch (error) {
message.warning("文件下载失败!");
console.error(error);
}
}
};