JavaScript文本转文件下载、下载图片、下载视频
下载媒体文件时,如果图片地址可以显示但是传过来的内容不是图片格式,使用封装方法downloadURI
不会进行下载,点击下载按钮后会跳转到这个图片页面。
如果使用方法downloadURI
不能下载需要请求下载资源之后进行下载
封装方法
javascript
export const downloadBlob = (blob: Blob, name: string) => {
// 创建一个下载链接并模拟点击
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
// 清理
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
/**
* 导出图像
* @param uri
* @param name
*/
export function downloadURI(uri: string, name: string) {
const link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Demo示例
示例方法中提供了两种下载方式分别是:Blob
和链接下载
html
<script lang="ts" setup>
import { ref } from 'vue';
import { downloadBlob, downloadURI } from '@/views/test/download/downloadUtil.ts';
const text = ref('文本内容...');
const image = 'https://gips2.baidu.com/it/u=1651586290,17201034&fm=3028&app=3028&f=JPEG&fmt=auto&q=100&size=f600_800';
const video = ref('https://videos.pexels.com/video-files/26806984/12011233_360_640_24fps.mp4');
/**
* * 下载文本
*/
const onDownloadText = () => {
const blob = new Blob([text.value], { type: 'text/plain;charset=utf-8' });
downloadBlob(blob, '下载文本.txt');
};
/**
* * 下载图片
*/
const onDownloadImage = () => {
const imageBlob = fetch(image).then(res => res.blob());
imageBlob.then(blob => downloadBlob(blob, 'blob图片.png'));
// 如果浏览器返回的不是图片格式会跳转到图片页面
downloadURI(image, 'a标签图片.png');
};
/**
* * 下载视频
*/
const onDownloadVideo = () => {
const imageBlob = fetch(video.value).then(res => res.blob());
imageBlob.then(blob => downloadBlob(blob, 'blob视频.mp4'));
downloadURI(video.value, 'a标签视频.mp4');
};
</script>
<template>
<div class="contain-layout">
<div>
<button class="btn btn-primary" @click="onDownloadText">下载文本</button>
<button class="btn btn-primary" @click="onDownloadImage">下载图片</button>
<button class="btn btn-primary" @click="onDownloadVideo">下载视频</button>
</div>
<div class="row mt-3">
<textarea :value="text" class="w-[400px]" />
<img :src="image" alt="" class="w-[150px] h-[150px]" />
<video :src="video" alt="" class="w-[300px] h-[300px]" />
</div>
</div>
</template>