前提:图片的地址链接需要先解决跨域,否则会出现新打开窗口预览图片,而不是直接下载
1.解决跨域
在vite.config.js文件中添加如下配置,vue-cli创建则在vue.config.js中配置
// vite.config.ts
import path from 'path'
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
...
// 配置代理
server: {
proxy: {
'/api': {
target: 'http://xxx.xx',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
2.实现web浏览器中图片的下载功能
// 提前存储设备的类型
uni.getSystemInfo({
success: function(res) {
uni.setStorageSync('deviceType', res.uniPlatform)
}
})
// 在功能函数中可以使用条件判断触发web浏览器的下载
if (uni.getStorageSync('deviceType') === 'web') {
url = url.replace('http://xxx.xx', '/api') // 使用代理请求图片
const aLink = document.createElement('a')
aLink.href = url
aLink.download = url.slice(url.lastIndexOf('/') + 1) // 设置保存是图片的名字(xxx.png|jpeg)
aLink.click() // 触发a链接的点击事件
return
}
3.手机浏览器效果图
当我点击下载按钮时触发下载功能