materialAttachments.vue 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <!-- 材料附件 -->
  2. <template>
  3. <view class="materialAttachments">
  4. <scroll-view scroll-y @scrolltolower="scrollGet" class="info-max-box">
  5. <view class="list">
  6. <view class="list-li" v-for="(item,index) in newData">
  7. <img :src="imagesUrl('safetyCheck/icon_djc_wj.png')">
  8. <view>{{item.fileName}}</view>
  9. <view @click="attachmentPreview(item)">查看</view>
  10. </view>
  11. </view>
  12. </scroll-view>
  13. </view>
  14. </template>
  15. <script>
  16. import {
  17. config
  18. } from '@/api/request/config.js'
  19. import {
  20. chemicalAppletGetStockDetail
  21. } from '@/pages/api/index.js'
  22. export default {
  23. name: "materialAttachments",
  24. components: {
  25. },
  26. data() {
  27. return {
  28. baseUrl: config.base_url,
  29. pageType: 0,
  30. newData: {},
  31. }
  32. },
  33. onLoad(option) {
  34. this.newData = JSON.parse(decodeURIComponent(option.infoData))
  35. },
  36. onShow() {
  37. },
  38. mounted() {
  39. },
  40. methods: {
  41. //滚动事件
  42. scrollGet() {},
  43. // 将此函数添加到 methods 中
  44. async attachmentPreview(item) {
  45. uni.showLoading({ title: '下载中' });
  46. const fileUrl = config.base_url + item.fileUrl;
  47. // #ifdef H5
  48. try {
  49. const response = await new Promise((resolve, reject) => {
  50. uni.request({
  51. url: fileUrl,
  52. method: 'GET',
  53. header: { Authorization: uni.getStorageSync('token') },
  54. responseType: 'arraybuffer', // 核心:使用 arraybuffer
  55. success: resolve,
  56. fail: reject,
  57. });
  58. });
  59. // 检查响应状态
  60. if (response.statusCode !== 200) {
  61. throw new Error(`下载失败,状态码: ${response.statusCode}`);
  62. }
  63. // 从 arraybuffer 创建 Blob 对象
  64. const blob = new Blob([response.data], {
  65. type: response.header['content-type'] || 'application/octet-stream'
  66. });
  67. const blobUrl = URL.createObjectURL(blob);
  68. const link = document.createElement('a');
  69. link.href = blobUrl;
  70. // 提取文件名
  71. let filename = this.getFileNameFromResponse(response, fileUrl);
  72. link.download = filename;
  73. document.body.appendChild(link);
  74. link.click();
  75. document.body.removeChild(link);
  76. URL.revokeObjectURL(blobUrl);
  77. uni.hideLoading();
  78. } catch (error) {
  79. console.error('下载失败:', error);
  80. uni.hideLoading();
  81. uni.showToast({ title: '下载失败', icon: 'none' });
  82. }
  83. // #endif
  84. // #ifdef MP-WEIXIN
  85. uni.downloadFile({
  86. url: config.base_url + item.fileUrl,
  87. header: {
  88. Authorization: uni.getStorageSync('token')
  89. },
  90. success: function(res) {
  91. uni.hideLoading();
  92. const filePath = res.tempFilePath
  93. wx.openDocument({
  94. filePath: filePath,
  95. success: function(res) {
  96. console.log('打开文档成功')
  97. }
  98. })
  99. },
  100. fail: function(res) {
  101. uni.hideLoading();
  102. uni.showToast({
  103. title: '下载失败',
  104. icon: "none",
  105. mask: true,
  106. duration: 2000
  107. });
  108. }
  109. })
  110. // #endif
  111. },
  112. // 辅助函数:从响应头或 URL 中解析文件名
  113. getFileNameFromResponse(response, fallbackUrl) {
  114. // 1. 从 Content-Disposition 响应头解析
  115. const contentDisposition = response.header['content-disposition'];
  116. if (contentDisposition) {
  117. // 匹配 filename*=UTF-8''encoded_filename 格式
  118. let match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i);
  119. if (match && match[1]) {
  120. return decodeURIComponent(match[1]);
  121. }
  122. // 匹配 filename="filename.pdf" 格式
  123. match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i);
  124. if (match && match[1]) {
  125. let filename = match[1].replace(/['"]/g, '');
  126. try {
  127. return decodeURIComponent(filename);
  128. } catch (e) {
  129. return filename;
  130. }
  131. }
  132. }
  133. // 2. 后备方案:从 URL 中提取
  134. let urlParts = fallbackUrl.split('/');
  135. let filename = urlParts[urlParts.length - 1].split('?')[0];
  136. // 3. 如果 URL 中也没有文件名,则根据 MIME 类型生成默认名
  137. if (!filename || filename === '') {
  138. const mimeToExt = {
  139. 'application/pdf': '.pdf',
  140. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',
  141. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
  142. };
  143. const contentType = response.header['content-type'];
  144. const extension = mimeToExt[contentType] || '.bin';
  145. filename = `download_${Date.now()}${extension}`;
  146. }
  147. return filename;
  148. },
  149. // attachmentPreview(item) {
  150. // uni.showLoading({
  151. // title: '下载中'
  152. // });
  153. // uni.downloadFile({
  154. // url: config.base_url + item.fileUrl,
  155. // header: {
  156. // Authorization: uni.getStorageSync('token')
  157. // },
  158. // success: function(res) {
  159. // uni.hideLoading();
  160. // // #ifdef MP-WEIXIN
  161. // const filePath = res.tempFilePath
  162. // wx.openDocument({
  163. // filePath: filePath,
  164. // success: function(res) {
  165. // console.log('打开文档成功')
  166. // }
  167. // })
  168. // // #endif
  169. // },
  170. // fail: function(res) {
  171. // uni.hideLoading();
  172. // uni.showToast({
  173. // title: '下载失败',
  174. // icon: "none",
  175. // mask: true,
  176. // duration: 2000
  177. // });
  178. // }
  179. // })
  180. // },
  181. }
  182. }
  183. </script>
  184. <style lang="stylus" scoped>
  185. .materialAttachments {
  186. height: 100%;
  187. display flex;
  188. box-sizing: border-box;
  189. padding: 0 30rpx;
  190. box-sizing: border-box;
  191. .list {
  192. width: 690rpx;
  193. background: #FFFFFF;
  194. border-radius: 20rpx 20rpx 20rpx 20rpx;
  195. padding: 0 30rpx;
  196. box-sizing: border-box;
  197. margin-bottom: 20rpx;
  198. margin-top: 20rpx;
  199. .list-li {
  200. height: 100rpx;
  201. border-bottom: 1rpx solid #E0E0E0;
  202. display: flex;
  203. justify-content: space-between;
  204. align-items: center;
  205. >img {
  206. width: 30rpx;
  207. height: 30rpx;
  208. margin-right: 16rpx;
  209. }
  210. >view:nth-of-type(1) {
  211. flex: 1;
  212. font-size: 28rpx;
  213. color: #333333;
  214. line-height: 39rpx;
  215. text-align: left;
  216. overflow: hidden;
  217. text-overflow: ellipsis;
  218. white-space: nowrap;
  219. margin-right: 56rpx;
  220. }
  221. >view:nth-of-type(2) {
  222. font-size: 28rpx;
  223. color: #0183FA;
  224. line-height: 39rpx;
  225. text-align: left;
  226. }
  227. }
  228. .list-li:last-of-type {
  229. border: none;
  230. }
  231. }
  232. }
  233. </style>