IOSDownLoad.vue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // pages/inedx/IOSDownLoad
  2. <template>
  3. <view>
  4. <button v-if="!isWeiXin" class="download-btn" type="default" @click="downLoad()">点击下载{{fileUrl}}</button>
  5. </view>
  6. </template>
  7. <script>
  8. export default {
  9. data() {
  10. return {
  11. isWeiXin: true,
  12. fileUrl:''
  13. };
  14. },
  15. onLoad(options) {
  16. if(options && options.url){
  17. this.fileUrl = options.url;
  18. console.log(this.fileUrl)
  19. }
  20. this.getIsWxClient();
  21. },
  22. methods: {
  23. // 判断是否是微信浏览器
  24. getIsWxClient() {
  25. const ua = navigator.userAgent.toLowerCase()
  26. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  27. this.isWeiXin = true;
  28. uni.showModal({
  29. title: '提示',
  30. content: '请点击右上角,在浏览器打开页面。',
  31. showCancel: false
  32. });
  33. } else {
  34. this.isWeiXin = false
  35. }
  36. },
  37. downLoad() {
  38. console.log('download')
  39. uni.showLoading({
  40. title: "正在请求数据"
  41. });
  42. uni.request({
  43. url: '/img'+this.fileUrl, //获取文件流的请求路径
  44. // url: '/api//img/1.pdf',
  45. responseType: "arraybuffer",
  46. success: (response) => {
  47. uni.hideLoading();
  48. console.log("response:", response)
  49. if (!response) {
  50. uni.showToast({
  51. title: "下载失败",
  52. duration: 2000
  53. });
  54. }
  55. let blob = new Blob([response.data]);
  56. let downloadElement = document.createElement("a");
  57. let href = window.URL.createObjectURL(blob); //创建下载的链接
  58. downloadElement.href = href;
  59. downloadElement.download = this.fileUrl; //下载后文件名
  60. document.body.appendChild(downloadElement);
  61. downloadElement.click(); //点击下载
  62. uni.showToast({
  63. title: "下载成功",
  64. duration: 2000
  65. });
  66. document.body.removeChild(downloadElement); //下载完成移除元素
  67. window.URL.revokeObjectURL(href); //释放掉blob对象
  68. }
  69. })
  70. }
  71. },
  72. }
  73. </script>
  74. <style lang="scss">
  75. .download-btn{
  76. width:50%;
  77. background:#3273BD;
  78. color:#fff;
  79. margin-top:100rpx;
  80. }
  81. </style>