Leanote's Blog
I love Leanote!
Toggle navigation
Leanote's Blog
Home
Chrome
Git
Linux
Windows
Others
工具大全
VsCode
Expo
Html
JavaScript
Npm
Node
Mock
React-Native
React
TypeScript
小程序
插件
正则
Dva
Ant-Design-React
Umi
Vue
Vux
Ant-Design-Vue
Http
Java
flutter
开发小工具
About Me
Archives
Tags
a标签下载文件和图片
2021-05-17 10:08:34
6
0
0
admin
### **注意, 跨域的图片地址不能下载, 会直接打开, 没跨域的可以下载** #### 第一个: 图片下载点击会打开新标签页, 解决: href的url后面加上`?response-content-type=application/octet-stream` ``` <a :href="item.url + '?response-content-type=application/octet-stream'" :download="item.name">点击下载</a> ``` #### 第二个 ``` // url为下载地址 fetch(url, { method: 'get', headers: { 'Content-Type': 'image/jpeg' } }).then( res => res.blob().then(blob => { var reader = new FileReader() reader.readAsDataURL(blob) // 转换为base64,可以直接放入a标签href reader.onload = function (e) { var downItem = document.createElement('a') // 转换完成,创建一个a标签用于下载 downItem.style.display = "none" downItem.download = name downItem.href = String(e.target.result) downItem.click() downItem.remove() // document.body.appendChild(downItem); // downItem.click() // document.body.removeChild(downItem); } }) ) ``` ### **通用方法: 跨域图片下载, 未跨域的也能下载** ``` /** * 图片转base64来下载 * @param imgSrc 图片地址 * @param imgName 未传的话, 优先截取图片地址后面的名称和图片类型 */ export function imgToBase64(imgSrc, imgName) { let imgType = "image/png" if (!imgName) { const arr = imgSrc.split("/") const imgMsgArr = arr[arr.length - 1].split(".") imgName = imgMsgArr[0] if (imgMsgArr[1]) imgType = "image/" + imgMsgArr[1] } const image = new Image() //解决跨域Canvas污染问题 image.setAttribute('crossOrigin', 'anonymous') image.onload = function () { const canvas = document.createElement('canvas') canvas.width = image.width canvas.height = image.height const context = canvas.getContext('2d') context.drawImage(image, 0, 0, image.width, image.height) const url = canvas.toDataURL(imgType) //生成一个a元素 let a = document.createElement('a') //将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘图片’作为默认名称 a.download = imgName || '图片' //将生成的URL设置为a.href属性 a.href = url //创建一个单击事件 const event = new MouseEvent('click') //触发a的单击事件 a.dispatchEvent(event) a = null } image.src = imgSrc; } ```
Pre:
element-ui的this.$confirm中提示的文字换行显示
Next:
js拼接动态正则
0
likes
6
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.