预加载
方式一:
let img = new Image();
img.src = data.accessUrl
方式二:
data.accessUrl ? fetch(data.accessUrl) : '';
缓存
服务器设置响应头Expires
和 Cache-Control
接口请求图片的缓存
一般接口默认不做数据缓存,所以当请求图片文件等资源时可以通过设置协商缓存来处理
Last-Modified
和 Etag
文件预览与下载
预览
a标签链接文件地址
get下载
window.open(文件地址);
ps:url没有域名,浏览器会根据当前环境自动加上
post下载
- 根据接口要求入参
- 添加请求头responseType: 'blob'或者,responseType: 'arraybuffer',表明响应类型
- 接口返回文件流
- 对文件流进行Blob转换,转换时注意要设置对应的转换类型,不然下载文件乱码
- 下载
- 以下为导出Excel文件代码
//接口
export const exportList = (data) => {
return $HttpService.commonRequest({
url: '/XXXX',
method: 'post',
data,
responseType: 'blob'
})
}
//接口请求
exportList(params).then(response => {
console.log('res,res', response)
const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' })
if ('download' in document.createElement('a')) {
const link = document.createElement('a')
link.download = '文件名.xlsx'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
} else {
navigator.msSaveBlob(blob)
}
})