IOSDownLoad.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // pages/inedx/IOSDownLoad
  2. <template>
  3. <view>
  4. <button v-if="!isWeiXin" class="download-btn" type="default" @click="downLoad()">点击下载pdf</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: '/video/txt.pdf', //获取文件流的请求路径
  44. responseType: "arraybuffer",
  45. success: (response) => {
  46. uni.hideLoading();
  47. console.log("response:", response)
  48. if (!response) {
  49. uni.showToast({
  50. title: "下载失败",
  51. duration: 2000
  52. });
  53. }
  54. let blob = new Blob([response.data]);
  55. let downloadElement = document.createElement("a");
  56. let href = window.URL.createObjectURL(blob); //创建下载的链接
  57. downloadElement.href = href;
  58. downloadElement.download = '文件.pdf'; //下载后文件名
  59. document.body.appendChild(downloadElement);
  60. downloadElement.click(); //点击下载
  61. uni.showToast({
  62. title: "下载成功",
  63. duration: 2000
  64. });
  65. document.body.removeChild(downloadElement); //下载完成移除元素
  66. window.URL.revokeObjectURL(href); //释放掉blob对象
  67. }
  68. })
  69. }
  70. },
  71. }
  72. </script>
  73. <style lang="scss">
  74. .download-btn{
  75. width:50%;
  76. background:#3273BD;
  77. color:#fff;
  78. margin-top:100rpx;
  79. }
  80. </style>