拓恒河湖长制全民护河平台WEB端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

235 lines
7.2KB

  1. // package_mine/pages/userInfo/index.js
  2. import {Base64} from 'js-base64'
  3. import {getOssAuth} from '../../../api/uploadOss.js'
  4. const crypto = require('crypto-js')
  5. import {uploadUserInfo} from '../../../api/mine.js'
  6. Page({
  7. /**
  8. * 页面的初始数据
  9. */
  10. data: {
  11. ossForm: {},
  12. form: {},
  13. image: '',
  14. formRules: {
  15. nickname: {
  16. validator: function (value) {
  17. return value;
  18. },
  19. warning: false
  20. },
  21. headimgurl: {
  22. validator: function (value) {
  23. return value;
  24. },
  25. warning: false
  26. }
  27. }
  28. },
  29. /**
  30. * 生命周期函数--监听页面加载
  31. */
  32. onLoad(options) {
  33. const form = wx.getStorageSync('userInfo')
  34. this.setData({form})
  35. },
  36. /**
  37. * 生命周期函数--监听页面初次渲染完成
  38. */
  39. onReady() {
  40. },
  41. /**
  42. * 生命周期函数--监听页面显示
  43. */
  44. onShow() {
  45. this.getOssAuthForm()
  46. },
  47. /**
  48. * 获取上传oss参数
  49. */
  50. getOssAuthForm() {
  51. let that = this
  52. getOssAuth().then((res)=> {
  53. let client = {
  54. region: 'oss-cn-shanghai',
  55. secure: true,
  56. accessKeyId: res.accessKeyId,
  57. accessKeySecret: res.accessKeySecret,
  58. securityToken: res.securityToken,
  59. bucket: 'ta-tech-image'
  60. }
  61. // 计算签名
  62. function computeSignature(accessKeySecret, canonicalString) {
  63. return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
  64. }
  65. const date = new Date();
  66. date.setHours(date.getHours() + 1);
  67. const policyText = {
  68. expiration: date.toISOString(), // 设置policy过期时间。
  69. conditions: [
  70. // 限制上传大小。
  71. ["content-length-range", 0, 1024 * 1024 * 1024],
  72. ],
  73. };
  74. // 获取签名
  75. const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
  76. const signature = computeSignature(client.accessKeySecret, policy)
  77. let ossForm = that.data.ossForm
  78. ossForm = {
  79. OSSAccessKeyId: client.accessKeyId,
  80. signature,
  81. policy,
  82. SecurityToken: client.securityToken
  83. }
  84. that.setData({ossForm})
  85. })
  86. },
  87. // 表单项验证
  88. validate(name) {
  89. let formRules = this.data.formRules;
  90. let validator = formRules[name].validator
  91. let result = validator ? !validator(this.data.form[name]) : false;
  92. formRules[name].warning = result
  93. this.setData({formRules})
  94. return result
  95. },
  96. // 表单验证
  97. validateForm() {
  98. return new Promise((resolve, reject) => {
  99. try {
  100. let formRules = this.data.formRules;
  101. let result = false;
  102. for (let key in formRules) {
  103. let temp = this.validate(key)
  104. if (temp) {
  105. result = temp
  106. }
  107. }
  108. resolve(!result)
  109. } catch (e) {
  110. reject(e)
  111. }
  112. })
  113. },
  114. // 输入
  115. bindValue(e) {
  116. let name = e.currentTarget.dataset.name;
  117. let form = this.data.form;
  118. form[name] = e.detail.value;
  119. this.setData({form})
  120. this.validate(name)
  121. },
  122. // 点击相机
  123. uploadAvatar() {
  124. wx.chooseMedia({
  125. count: 1, // 最多可以选择的图片张数,默认9
  126. mediaType: ['image'], // 图片
  127. sizeType: ['original'], // original 原图,compressed 压缩图,默认二者都有
  128. sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
  129. success:(res) =>{
  130. const list = res.tempFiles.map((item)=> {
  131. return item.tempFilePath
  132. })
  133. // success
  134. let form = this.data.form
  135. form.headimgurl = list[0]
  136. this.setData({ form, image: list[0] })
  137. this.validate('headimgurl')
  138. },
  139. fail: (e) => {
  140. console.log(e, '取消选择');
  141. }
  142. })
  143. },
  144. /**
  145. * 图片上传oss
  146. */
  147. uploadToOss(url) {
  148. const ossForm = this.data.ossForm
  149. // 设置文件上传路径
  150. const randomString = Math.random().toString(36).slice(2)
  151. const timestamp = new Date().getTime()
  152. const key = `imagedir/${randomString}_${timestamp}.png`
  153. // 上传图片
  154. return new Promise((resolve, reject)=> {
  155. wx.uploadFile({
  156. url: 'https://ta-tech-image.oss-cn-shanghai.aliyuncs.com',
  157. filePath: url,
  158. name: 'file',
  159. formData: {
  160. key,
  161. OSSAccessKeyId: ossForm.OSSAccessKeyId,
  162. signature: ossForm.signature,
  163. policy: ossForm.policy,
  164. 'x-oss-security-token': ossForm.SecurityToken
  165. },
  166. success: (res)=> {
  167. if(res.statusCode === 204) {
  168. // 上传成功,将图片路径resolve出去
  169. resolve(key)
  170. } else {
  171. wx.showToast({
  172. title: '图片上传失败',
  173. })
  174. reject('图片上传失败')
  175. }
  176. },
  177. fail: (e)=> {
  178. console.log(e);
  179. reject('图片上传失败')
  180. }
  181. })
  182. })
  183. },
  184. /* 表单上传 */
  185. submit(){
  186. this.validateForm().then(res => {
  187. if(res) {
  188. const image = this.data.image
  189. let params = {}
  190. params.id = this.data.form.id
  191. params.nickname = this.data.form.nickname
  192. if (image) {
  193. wx.showLoading({title:"上传中",mask:true})
  194. this.uploadToOss(image).then(item=> {
  195. params.headimgurl = item
  196. uploadUserInfo(params).then(i => {
  197. if (i.code === 0) {
  198. wx.switchTab({
  199. url: '/pages/mine/index',
  200. })
  201. }
  202. }).finally(()=>{
  203. wx.hideLoading();
  204. })
  205. }).catch(()=> {
  206. wx.hideLoading();
  207. })
  208. } else {
  209. uploadUserInfo(params).then(i => {
  210. if (i.code === 0) {
  211. wx.switchTab({
  212. url: '/pages/mine/index',
  213. })
  214. }
  215. }).finally(()=>{
  216. wx.hideLoading();
  217. })
  218. }
  219. }
  220. })
  221. }
  222. })