Files
Miniprogram/pages/index/index.js
2025-12-17 14:21:57 +08:00

146 lines
3.3 KiB
JavaScript

// index.js
const app = getApp()
Page({
data: {
imagePath: '',
speedMode: false
},
onLoad: function() {
// 页面加载时执行
},
// 加速模式开关切换事件
toggleSpeedMode: function(e) {
this.setData({
speedMode: e.detail.value
})
},
// 扫码按钮点击事件
scanCode: function() {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePath = res.tempFilePaths[0]
this.setData({
imagePath: tempFilePath
})
// 上传图片到后台
this.uploadImage(tempFilePath)
},
fail: (err) => {
console.error('选择图片失败:', err)
wx.showToast({
title: '选择图片失败',
icon: 'none'
})
}
})
},
// 上传图片到后台
uploadImage: function(filePath) {
wx.showLoading({
title: '上传中...',
})
wx.uploadFile({
url: 'https://227649ip14.51mypc.cn/api/upload', // 替换为你的后台接口地址
filePath: filePath,
name: 'image',
formData: {
type: this.data.speedMode ? 1 : 0
},
header: {
'content-type': 'multipart/form-data'
},
success: (res) => {
wx.hideLoading()
wx.showToast({
title: '上传成功',
icon: 'success'
})
console.log('上传结果:', res)
},
fail: (err) => {
wx.hideLoading()
wx.showToast({
title: '上传失败',
icon: 'none'
})
console.error('上传失败:', err)
}
})
},
// 用户认证按钮点击事件
userAuth: function() {
wx.login({
success: (res) => {
if (res.code) {
// 使用code换取openid
this.getOpenid(res.code)
} else {
console.error('登录失败:', res.errMsg)
wx.showToast({
title: '登录失败',
icon: 'none'
})
}
},
fail: (err) => {
console.error('调用登录接口失败:', err)
wx.showToast({
title: '登录接口调用失败',
icon: 'none'
})
}
})
},
// 使用code换取openid
getOpenid: function(code) {
wx.showLoading({
title: '获取openid中...',
})
wx.request({
url: 'https://227649ip14.51mypc.cn/app/wechat-mini-app/getOpenid', // 替换为你的后台接口地址
method: 'POST',
data: {
code: code
},
success: (res) => {
wx.hideLoading()
if (res.data.openid) {
app.globalData.openid = res.data.openid
wx.showToast({
title: '认证成功',
icon: 'success'
})
console.log('获取到的openid:', res.data.openid)
} else {
wx.showToast({
title: '认证失败',
icon: 'none'
})
console.error('认证失败:', res.data)
}
},
fail: (err) => {
wx.hideLoading()
wx.showToast({
title: '网络请求失败',
icon: 'none'
})
console.error('网络请求失败:', err)
}
})
}
})