diff --git a/api/upload.js b/api/upload.js index fdca560..104dc2d 100644 --- a/api/upload.js +++ b/api/upload.js @@ -1,105 +1,29 @@ -import request from './request' - -const uploadFile = async (file, callback) => { - const policyData = await request('admin/policy_token', 'post') - const res = JSON.parse(policyData.token) - - const fileName = file.tempFilePath.split('/').pop(); // hello.png - // const fileName = fileNameWithExt.split('.').slice(0, -1).join('.'); // hello - - const formData = { - key: 'upload_file/' + fileName, //上传文件名称 - policy: res.policy, //表单域 - 'x-oss-signature-version': res.x_oss_signature_version, //指定签名的版本和算法 - 'x-oss-credential': res.x_oss_credential, //指明派生密钥的参数集 - 'x-oss-date': res.x_oss_date, //请求的时间 - 'x-oss-signature': res.signature, //签名认证描述信息 - 'x-oss-security-token': res.security_token, //安全令牌 - success_action_status: "200" //上传成功后响应状态码 - }; - // console.log(filePath) - // return - // 发送请求上传文件 - wx.uploadFile({ - url: 'https://image-fudan.oss-cn-beijing.aliyuncs.com/', - method: 'put', - filePath: file.tempFilePath, - name: 'file', //固定值为file - formData: formData, - success(res) { - console.log('上传响应:', res); - if (res.statusCode === 200) { - callback(null, 'https://image-fudan.oss-cn-beijing.aliyuncs.com/upload_file/' + fileName); // 上传成功 - } else { - console.error('上传失败,状态码:', res.statusCode); - console.error('失败响应:', res); - callback(res); // 上传失败,返回响应 - } - }, - fail(err) { - console.error('上传失败:', err); // 输出错误信息 - wx.showToast({ - title: '上传失败,请重试!', - icon: 'none' - }); - callback(err); // 调用回调处理错误 +function uploadFile(filePath) { + return new Promise((resolve, reject) => { + if (!filePath) { + const err = new Error('uploadFile requires a filePath parameter'); + console.error('上传失败:未提供文件路径', err); + return reject(err); } - }); + + wx.uploadFile({ + filePath: filePath, // 图片临时文件路径(由调用方传入) + name: 'file', // 服务器接收文件的字段名,需与后端对应 + url: 'https://mini-chat.1024tool.vip/api/admin/upload/image', // 服务器接收图片的接口地址 + success: (res) => { + resolve(res); + }, + fail: (err) => { + console.error('上传失败', err); + reject(err); + } + }); + }) } -const uploadFileToOSS = () => { - - return new Promise((resolve, reject) => { - - wx.chooseMedia({ - count: 1, // 选择一个文件 - mediaType: ['image'], - sourceType: ['album', 'camera'], - // type: 'all', // 支持所有类型的文件 - success: (res) => { - wx.showToast({ - title: '文件上传中,请稍等!', - icon: 'none' - }); - console.log('选择的文件:', res.tempFiles); // 输出选择的文件信息 - if (res.tempFiles.length > 0) { - const tempFilePath = res.tempFiles[0]; - console.log('选择的文件路径:', tempFilePath); // 输出文件路径 - uploadFile(tempFilePath, (error, data) => { - if (error) { - wx.showToast({ - title: '上传失败!', - icon: 'none' - }); - console.error('上传失败:', error); // 输出具体的错误信息 - reject(error) - } else { - resolve(data) - console.log('上传成功:', data); // 输出上传成功后的数据 - } - }); - } else { - wx.showToast({ - title: '未选择文件!', - icon: 'none' - }); - reject('未选择文件!') - } - }, - fail: (err) => { - wx.showToast({ - title: '选择文件失败!', - icon: 'none' - }); - console.error('选择文件失败:', err); // 输出选择文件的错误信息 - reject('选择文件失败!') - } - }); - }); -}; - -export default uploadFileToOSS; \ No newline at end of file +// 导出请求和服务地址(CommonJS 兼容) +module.exports = uploadFile; \ No newline at end of file diff --git a/pages/contact/index.js b/pages/contact/index.js index 73fb627..9aeca6f 100644 --- a/pages/contact/index.js +++ b/pages/contact/index.js @@ -1,7 +1,7 @@ // pages/contact/index.js const request = require('../../api/request.js'); - +const uploadFile = require('../../api/upload.js'); Page({ /** * 页面的初始数据 @@ -73,18 +73,18 @@ Page({ }).then(res => { // 处理消息列表,使用统一的消息处理函数 const list = that.processMessages(res.list); - + // 根据ID进行排序,确保ID最大的(最新的)消息在最后 const sortedList = that.sortMessagesByID(list); - + // 智能滚动逻辑:用户在底部时自动滚动,在上方时保持位置 const updateData = { messages: sortedList, total: res.total }; - + that.setData(updateData); - + // 如果用户在底部,延迟设置滚动ID确保滚动生效 if (that.data.isAtBottom && sortedList.length > 0) { const lastMessageId = sortedList[sortedList.length - 1].id; @@ -98,7 +98,7 @@ Page({ } else { console.log('用户不在底部或无消息,保持当前位置。isAtBottom:', that.data.isAtBottom, '消息数量:', sortedList.length); } - + return res; // 返回结果以支持链式调用 }); }, @@ -131,7 +131,7 @@ Page({ // 合并新消息和现有消息 const combined = newList.concat(that.data.messages); - + // 根据ID进行排序,确保ID最大的(最新的)消息在最后 const sortedCombined = that.sortMessagesByID(combined); @@ -165,7 +165,7 @@ Page({ // 兜底方案:使用当前时间戳 + 索引 item.id = 'm' + (Date.now() + index); } - + // 解析消息内容 if (typeof item.content === 'string') { try { @@ -175,31 +175,31 @@ Page({ item.content = { messages: item.content }; } } - + return item; }); // 检测新消息并显示提醒 this.checkNewMessages(processedMessages); - + return processedMessages; }, // 检测新消息的函数 checkNewMessages(newMessages) { if (newMessages.length === 0) return; - + const currentMessages = this.data.messages; const currentLastMessageId = this.data.lastMessageId; const sortedNewMessages = this.sortMessagesByID(newMessages); const latestNewMessage = sortedNewMessages[sortedNewMessages.length - 1]; - + // 如果不在底部且有新消息 if (!this.data.isAtBottom && currentMessages.length > 0) { // 找出真正的新消息(在当前消息列表中不存在的消息) const currentMessageIds = new Set(currentMessages.map(msg => msg.id)); const realNewMessages = sortedNewMessages.filter(msg => !currentMessageIds.has(msg.id)); - + if (realNewMessages.length > 0) { // 累加新消息数量(而不是重置) const currentCount = this.data.newMessageCount || 0; @@ -209,7 +209,7 @@ Page({ }); } } - + // 更新最后一条消息ID if (latestNewMessage) { this.setData({ @@ -239,7 +239,7 @@ Page({ } return 0; }; - + const idA = getNumericId(a.id); const idB = getNumericId(b.id); return idA - idB; @@ -282,7 +282,7 @@ Page({ }); }); }, - fail: function(err) { + fail: function (err) { console.error('wx.login失败:', err); } }); @@ -337,7 +337,7 @@ Page({ // user scrolled to bottom (or very near). update state and ensure polling is active console.log('用户滚动到底部,当前isAtBottom状态:', this.data.isAtBottom); if (!this.data.isAtBottom) { - this.setData({ + this.setData({ isAtBottom: true, showNewMessageTip: false, newMessageCount: 0 @@ -392,7 +392,7 @@ Page({ // 使用用户ID作为标记,检查是否已经发送过欢迎消息 const welcomeKey = `welcome_sent_${this.data.userInfo.openid}`; const hasWelcomeSent = wx.getStorageSync(welcomeKey); - + if (hasWelcomeSent) { console.log('该用户的欢迎消息已发送过,跳过'); this.setData({ hasWelcomeMessageSent: true }); @@ -402,7 +402,7 @@ Page({ const welcomeText = '你好'; const now = new Date(); const id = 'welcome_' + Date.now(); - + const msg = { id, content: { @@ -414,11 +414,11 @@ Page({ sender_id: this.data.userInfo.openid, sender_name: this.data.userInfo.user_name }; - + // 添加新消息并重新排序 const newMessages = this.data.messages.concat(msg); const sortedMessages = this.sortMessagesByID(newMessages); - + this.setData({ messages: sortedMessages, hasWelcomeMessageSent: true // 标记已发送欢迎消息 @@ -426,9 +426,9 @@ Page({ const accountInfo = wx.getAccountInfoSync(); const userInfo = wx.getStorageSync('user_info'); - + console.log('发送欢迎消息:', welcomeText); - + // 发送到服务器 request('app/send_message', 'POST', { "app_id": accountInfo.miniProgram.appId, @@ -478,11 +478,11 @@ Page({ sender_id: this.data.userInfo.openid, sender_name: this.data.userInfo.user_name }; - + // 添加新消息并重新排序 const newMessages = this.data.messages.concat(msg); const sortedMessages = this.sortMessagesByID(newMessages); - + this.setData({ messages: sortedMessages, inputText: '' @@ -567,30 +567,42 @@ Page({ scrollToId: id }); }, 50); + uploadFile(tempFilePaths[0]).then((res) => { + const data = JSON.parse(res.data); + console.log('上传成功', data); + const accountInfo = wx.getAccountInfoSync(); - wx.uploadFile({ - filePath: tempFilePaths[0], // 图片临时文件路径 - name: 'file', // 服务器接收文件的字段名,需与后端对应 - url: 'https://mini-chat.1024tool.vip/admin/upload/image', // 服务器接收图片的接口地址 - success: (res) => { - const data = JSON.parse(res.data); - console.log('上传成功', data); - const accountInfo = wx.getAccountInfoSync(); - - request('app/send_message', 'POST', { - "app_id": accountInfo.miniProgram.appId, - "content": JSON.stringify({ - messages: 'https://mini-chat.1024tool.vip/'+ data.preview_image_url - }), - "from_user_id": userInfo.openid, - "from_user_name": userInfo.user_name, - "msg_type": 2 - }) - }, - fail: (err) => { - console.error('上传失败', err); - } + request('app/send_message', 'POST', { + "app_id": accountInfo.miniProgram.appId, + "content": JSON.stringify({ + messages: 'https://mini-chat.1024tool.vip/' + data.preview_image_url + }), + "from_user_id": userInfo.openid, + "from_user_name": userInfo.user_name, + "msg_type": 2 + }).catch((err) => { + wx.showToast({ + title: '图片发送失败', + icon: 'none' + }); + }); + }).catch((err) => { + wx.showToast({ + title: '图片发送失败', + icon: 'none' + }); }); + // wx.uploadFile({ + // filePath: tempFilePaths[0], // 图片临时文件路径 + // name: 'file', // 服务器接收文件的字段名,需与后端对应 + // url: 'https://mini-chat.1024tool.vip/api/admin/upload/image', // 服务器接收图片的接口地址 + // success: (res) => { + + // }, + // fail: (err) => { + // console.error('上传失败', err); + // } + // }); // 模拟客服返回图片确认 // setTimeout(() => { @@ -674,14 +686,14 @@ Page({ if (messages.length > 0) { const sortedMessages = this.sortMessagesByID(messages); const latestMessage = sortedMessages[sortedMessages.length - 1]; - + this.setData({ scrollToId: latestMessage.id, showNewMessageTip: false, newMessageCount: 0, isAtBottom: true }); - + // 延迟一下确保滚动完成 setTimeout(() => { this.setData({ diff --git a/project.config.json b/project.config.json index 867bf7e..6b7fbb2 100644 --- a/project.config.json +++ b/project.config.json @@ -6,13 +6,13 @@ "appid": "wx26ad074017e1e63f", "libVersion": "3.9.2", "setting": { - "es6": false, + "es6": true, "postcss": false, "compileWorklet": false, "minified": false, "uglifyFileName": false, "uploadWithSourceMap": true, - "enhance": false, + "enhance": true, "packNpmManually": false, "packNpmRelationList": [], "minifyWXSS": true, diff --git a/project.private.config.json b/project.private.config.json index be03d0b..af6a3b7 100644 --- a/project.private.config.json +++ b/project.private.config.json @@ -32,7 +32,7 @@ { "name": "pages/index/detail", "pathName": "pages/index/detail", - "query": "", + "query": "url=1", "launchMode": "default", "scene": null }