index.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <template>
  2. <div class="file-upload-container">
  3. <div class="header">
  4. <h2>文件上传</h2>
  5. <!-- <p>选择文件后提交给小程序</p>
  6. <p v-if="type" class="type-info">当前类型: {{ type }}</p>
  7. <p v-else class="type-info">未设置类型参数</p> -->
  8. </div>
  9. <div class="upload-area" @click="triggerFileInput">
  10. <div class="upload-icon">
  11. <i class="el-icon-upload"></i>
  12. </div>
  13. <div class="upload-text">
  14. <p>点击选择文件</p>
  15. <p class="upload-hint">支持图片、文档、压缩文件、视频/音频等格式</p>
  16. </div>
  17. <input
  18. ref="fileInput"
  19. type="file"
  20. multiple
  21. accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt,.mp4,.mp3"
  22. @change="handleFileSelect"
  23. style="display: none"
  24. />
  25. </div>
  26. <div v-if="selectedFiles.length > 0" class="file-list">
  27. <h3>已选择的文件</h3>
  28. <div class="file-item" v-for="(file, index) in selectedFiles" :key="index">
  29. <div class="file-info">
  30. <div class="file-icon">
  31. <i :class="getFileIcon(file.type)"></i>
  32. </div>
  33. <div class="file-details">
  34. <div class="file-name">{{ file.name }}</div>
  35. <div class="file-size">{{ formatFileSize(file.size) }}</div>
  36. <div class="file-status">
  37. <span v-if="uploadedFiles[index]" class="status-success">
  38. <i class="el-icon-check"></i> 已上传
  39. </span>
  40. <span v-else class="status-uploading">
  41. <i class="el-icon-loading"></i> 上传中...
  42. </span>
  43. </div>
  44. </div>
  45. </div>
  46. <div class="file-actions">
  47. <el-button
  48. type="danger"
  49. size="mini"
  50. @click="removeFile(index)"
  51. icon="el-icon-delete"
  52. >
  53. 删除
  54. </el-button>
  55. </div>
  56. </div>
  57. </div>
  58. <div class="submit-area">
  59. <el-button
  60. type="primary"
  61. size="large"
  62. @click="submitToMiniProgram"
  63. :disabled="uploadedFiles.length === 0"
  64. :loading="submitting"
  65. >
  66. {{ submitting ? '提交中...' : '提交文件' }} ({{ uploadedFiles.length }}个文件)
  67. </el-button>
  68. </div>
  69. </div>
  70. </template>
  71. <script>
  72. import wx from 'weixin-js-sdk'
  73. export default {
  74. name: 'FileUpload',
  75. data() {
  76. return {
  77. selectedFiles: [],
  78. uploadedFiles: [], // 存储上传后的文件URL
  79. submitting: false,
  80. type: '' // 从URL接收的type参数
  81. }
  82. },
  83. mounted() {
  84. this.checkWechatEnvironment()
  85. this.getTypeFromUrl()
  86. },
  87. methods: {
  88. // 从URL获取type参数
  89. getTypeFromUrl() {
  90. try {
  91. // 方法1: 使用URLSearchParams
  92. const urlParams = new URLSearchParams(window.location.search)
  93. this.type = urlParams.get('type') || ''
  94. // 如果URLSearchParams获取不到,尝试其他方法
  95. if (!this.type) {
  96. // 方法2: 使用正则表达式
  97. const match = window.location.search.match(/[?&]type=([^&]*)/)
  98. if (match) {
  99. this.type = decodeURIComponent(match[1])
  100. }
  101. }
  102. // 方法3: 使用Vue Router的query参数
  103. if (!this.type && this.$route && this.$route.query) {
  104. this.type = this.$route.query.type || ''
  105. }
  106. console.log('当前URL:', window.location.href)
  107. console.log('URL查询参数:', window.location.search)
  108. console.log('从URL接收的type参数:', this.type)
  109. console.log('Vue Router query:', this.$route ? this.$route.query : '无路由信息')
  110. // 如果还是没有获取到,显示提示
  111. if (!this.type) {
  112. console.warn('未找到type参数,请检查URL格式,例如: ?type=image')
  113. }
  114. } catch (error) {
  115. console.error('获取type参数时出错:', error)
  116. }
  117. },
  118. // 检查微信环境
  119. checkWechatEnvironment() {
  120. const isWechat = /micromessenger/i.test(navigator.userAgent)
  121. if (!isWechat) {
  122. this.$message.warning('请在微信中打开此页面')
  123. }
  124. },
  125. // 触发文件选择
  126. triggerFileInput() {
  127. this.$refs.fileInput.click()
  128. },
  129. // 处理文件选择
  130. async handleFileSelect(event) {
  131. const files = Array.from(event.target.files)
  132. for (const file of files) {
  133. // 检查文件大小限制 (50MB)
  134. if (file.size > 50 * 1024 * 1024) {
  135. this.$message.error(`文件 ${file.name} 超过50MB限制`)
  136. continue
  137. }
  138. // 检查是否已存在同名文件
  139. const exists = this.selectedFiles.find(f => f.name === file.name)
  140. if (exists) {
  141. this.$message.warning(`文件 ${file.name} 已存在`)
  142. continue
  143. }
  144. // 添加到选中文件列表
  145. this.selectedFiles.push(file)
  146. // 上传文件并获取URL
  147. try {
  148. await this.uploadFile(file)
  149. } catch (error) {
  150. console.error(`上传文件 ${file.name} 失败:`, error)
  151. this.$message.error(`上传文件 ${file.name} 失败`)
  152. }
  153. }
  154. // 清空input值,允许重复选择同一文件
  155. event.target.value = ''
  156. },
  157. // 删除文件
  158. removeFile(index) {
  159. this.selectedFiles.splice(index, 1)
  160. // 同时删除对应的上传文件信息
  161. if (this.uploadedFiles[index]) {
  162. this.uploadedFiles.splice(index, 1)
  163. }
  164. },
  165. // 获取文件图标
  166. getFileIcon(type) {
  167. if (type.startsWith('image/')) {
  168. return 'el-icon-picture'
  169. } else if (type.includes('pdf')) {
  170. return 'el-icon-document'
  171. } else if (type.includes('word') || type.includes('document')) {
  172. return 'el-icon-document'
  173. } else if (type.includes('excel') || type.includes('spreadsheet')) {
  174. return 'el-icon-document'
  175. } else if (type.includes('video')) {
  176. return 'el-icon-video-camera'
  177. } else if (type.includes('audio')) {
  178. return 'el-icon-headset'
  179. } else {
  180. return 'el-icon-document'
  181. }
  182. },
  183. // 格式化文件大小
  184. formatFileSize(bytes) {
  185. if (bytes === 0) return '0 B'
  186. const k = 1024
  187. const sizes = ['B', 'KB', 'MB', 'GB']
  188. const i = Math.floor(Math.log(bytes) / Math.log(k))
  189. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  190. },
  191. // 提交给小程序
  192. async submitToMiniProgram() {
  193. if (this.uploadedFiles.length === 0) {
  194. this.$message.warning('请先选择并上传文件')
  195. return
  196. }
  197. this.submitting = true
  198. try {
  199. // 检查微信环境
  200. if (typeof WeixinJSBridge === 'undefined') {
  201. this.$message.error('请在微信中打开此页面')
  202. return
  203. }
  204. // 通过微信JS-SDK发送消息给小程序
  205. if (wx && wx.miniProgram) {
  206. // 在微信小程序web-view中
  207. wx.miniProgram.postMessage({
  208. data: {
  209. type: 'file_upload',
  210. files: this.uploadedFiles
  211. }
  212. })
  213. this.$message.success('文件已提交给小程序')
  214. this.selectedFiles = []
  215. this.uploadedFiles = []
  216. // 延迟关闭web-view,让用户看到成功提示
  217. setTimeout(() => {
  218. wx.miniProgram.navigateBack({
  219. delta: 1
  220. })
  221. }, 1500)
  222. } else {
  223. // 如果不在小程序web-view中,提示用户
  224. this.$message.error('请在微信小程序中打开此页面')
  225. }
  226. } catch (error) {
  227. console.error('提交文件失败:', error)
  228. this.$message.error('提交失败,请重试')
  229. } finally {
  230. this.submitting = false
  231. }
  232. },
  233. uploadFile(file) {
  234. return new Promise((resolve, reject) => {
  235. const formData = new FormData();
  236. formData.append('file', file);
  237. this.$store.dispatch('pool/uploadFile', formData).then(res => {
  238. if(res.code == 200){
  239. const fileInfo = {
  240. imgUrl:res.data.imgUrl,
  241. id:res.data.id,
  242. src:res.data.src,
  243. fileName:res.data.fileName,
  244. fileType:res.data.fileType,
  245. oldFileName:res.data.oldFileName,
  246. oldName:res.data.oldName,
  247. type: this.type, // 添加从URL接收的type参数
  248. };
  249. // 添加到已上传文件列表
  250. this.uploadedFiles.push(fileInfo);
  251. console.log('文件上传成功:', fileInfo);
  252. resolve(fileInfo);
  253. }else{
  254. this.$message({
  255. type: 'info',
  256. message: res.message
  257. });
  258. // 从selectedFiles中删除上传失败的文件
  259. const fileIndex = this.selectedFiles.findIndex(f => f.name === file.name);
  260. if (fileIndex !== -1) {
  261. this.selectedFiles.splice(fileIndex, 1);
  262. }
  263. reject(res.message);
  264. }
  265. }).catch((error) => {
  266. console.error('文件上传失败:', error);
  267. this.$message({
  268. type: 'error',
  269. message: `上传文件 ${file.name} 失败,请重试!`
  270. });
  271. // 从selectedFiles中删除上传失败的文件
  272. const fileIndex = this.selectedFiles.findIndex(f => f.name === file.name);
  273. if (fileIndex !== -1) {
  274. this.selectedFiles.splice(fileIndex, 1);
  275. }
  276. reject(error);
  277. });
  278. });
  279. },
  280. }
  281. }
  282. </script>
  283. <style scoped>
  284. .file-upload-container {
  285. max-width: 800px;
  286. margin: 0 auto;
  287. padding: 20px;
  288. background: #fff;
  289. min-height: 100vh;
  290. }
  291. .header {
  292. text-align: center;
  293. margin-bottom: 30px;
  294. }
  295. .header h2 {
  296. color: #303133;
  297. margin-bottom: 10px;
  298. }
  299. .header p {
  300. color: #909399;
  301. font-size: 14px;
  302. }
  303. .type-info {
  304. background: #f0f9ff;
  305. border: 1px solid #409eff;
  306. border-radius: 4px;
  307. padding: 8px 12px;
  308. margin-top: 10px;
  309. font-size: 12px;
  310. color: #409eff;
  311. }
  312. .upload-area {
  313. border: 2px dashed #d9d9d9;
  314. border-radius: 8px;
  315. padding: 40px;
  316. text-align: center;
  317. cursor: pointer;
  318. transition: all 0.3s;
  319. background: #fafafa;
  320. }
  321. .upload-area:hover {
  322. border-color: #409eff;
  323. background: #f0f9ff;
  324. }
  325. .upload-icon {
  326. font-size: 48px;
  327. color: #c0c4cc;
  328. margin-bottom: 20px;
  329. }
  330. .upload-text p {
  331. margin: 5px 0;
  332. color: #606266;
  333. }
  334. .upload-hint {
  335. font-size: 12px;
  336. color: #c0c4cc;
  337. }
  338. .file-list {
  339. margin-top: 30px;
  340. }
  341. .file-list h3 {
  342. margin-bottom: 15px;
  343. color: #303133;
  344. }
  345. .file-item {
  346. display: flex;
  347. align-items: center;
  348. justify-content: space-between;
  349. padding: 15px;
  350. border: 1px solid #ebeef5;
  351. border-radius: 6px;
  352. margin-bottom: 10px;
  353. background: #fff;
  354. transition: all 0.3s;
  355. }
  356. .file-item:hover {
  357. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  358. }
  359. .file-info {
  360. display: flex;
  361. align-items: center;
  362. flex: 1;
  363. }
  364. .file-icon {
  365. font-size: 24px;
  366. color: #409eff;
  367. margin-right: 15px;
  368. }
  369. .file-details {
  370. flex: 1;
  371. }
  372. .file-name {
  373. font-weight: 500;
  374. color: #303133;
  375. margin-bottom: 5px;
  376. word-break: break-all;
  377. }
  378. .file-size {
  379. font-size: 12px;
  380. color: #909399;
  381. }
  382. .file-status {
  383. margin-top: 5px;
  384. }
  385. .status-success {
  386. color: #67c23a;
  387. font-size: 12px;
  388. }
  389. .status-success i {
  390. margin-right: 3px;
  391. }
  392. .status-uploading {
  393. color: #e6a23c;
  394. font-size: 12px;
  395. }
  396. .status-uploading i {
  397. margin-right: 3px;
  398. animation: rotating 2s linear infinite;
  399. }
  400. @keyframes rotating {
  401. from {
  402. transform: rotate(0deg);
  403. }
  404. to {
  405. transform: rotate(360deg);
  406. }
  407. }
  408. .file-actions {
  409. margin-left: 15px;
  410. }
  411. .submit-area {
  412. margin-top: 30px;
  413. text-align: center;
  414. }
  415. /* 响应式设计 */
  416. @media (max-width: 768px) {
  417. .file-upload-container {
  418. padding: 15px;
  419. }
  420. .upload-area {
  421. padding: 30px 20px;
  422. }
  423. .file-item {
  424. flex-direction: column;
  425. align-items: flex-start;
  426. }
  427. .file-actions {
  428. margin-left: 0;
  429. margin-top: 10px;
  430. align-self: flex-end;
  431. }
  432. }
  433. </style>