前端直接下载图片和PDF文件的方案,现在很多浏览器都会拦截图片和pdf直接预览,使用流下载的方式可以跳过浏览器的拦截直接下载。
这里提供一个方法,传入文件名和下载地址就可以了,如果后端直接返回流或者直接返回图片,都会直接下载。
/** * @param url 文件的下载地址 * @param filename 下载下来的文件名 */handleLink(url, filename) { fetch(url, { method: 'get', responseType: 'arraybuffer', }).then((res) => { return res.arrayBuffer() }).then((blobRes) => { // 生成 Blob 对象,设置 type 等信息 const e = new Blob([blobRes], { type: 'application/octet-stream', 'Content-Disposition': 'attachment'12 collapsed lines
}) // 将 Blob 对象转为 url const link = window.URL.createObjectURL(e) // 创建 a 标签 let a = document.createElement('a'); a.href = link; a.download = filename; a.click(); }).catch(err => { console.error(err) })}