云开发是腾讯云提供的云原生一体化开发环境和工具平台,为开发者提供高可用、主动弹性扩缩的后端云服务,可用于云端一体化开发多种端利用。
开发流程
代码引入
在以后页面的.json 中引入组件
{ "usingComponents": { "mp-uploader": "weui-miniprogram/uploader/uploader" }}
代码开发
在以后页面.wxml中编写上传组件
<view class="page__bd"> <mp-cells> <mp-cell> <mp-uploader bindfail="uploadError" bindsuccess="uploadSuccess" select="{{selectFile}}" upload="{{uplaodFile}}" files="{{files}}" max-count="4" title="附件上传" tips="最多可上传4张照片"></mp-uploader> </mp-cell> </mp-cells> </view>
bindfail 图片上传失败的事件,detail为{type, errMsg},type为1示意图片超过大小限度,type为2示意抉择图片失败,type为3示意图片上传失败。
bindselect 图片抉择触发的事件,detail为{tempFilePaths, tempFiles, contents},其中tempFiles和tempFilePaths是chooseImage返回的字段,contents示意所选的图片的二进制Buffer列表
max-count 图片上传的个数限度
在以后页面的.js中编写
wx.cloud.init({ env: '环境ID', traceUser: true,}) formInputChange(e) { const { field } = e.currentTarget.dataset this.setData({ [`formData.${field}`]: e.detail.value }) },chooseImage: function (e) { var that = this; wx.chooseImage({ sizeType: ['original', 'compressed'], // 能够指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 能够指定起源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件门路列表,tempFilePath能够作为img标签的src属性显示图片 that.setData({ files: that.data.files.concat(res.tempFilePaths) }); } })},previewImage: function(e){ wx.previewImage({ current: e.currentTarget.id, // 以后显示图片的http链接 urls: this.data.files // 须要预览的图片http链接列表 })},selectFile(files) { console.log('files', files) // 返回false能够阻止某次文件上传},uplaodFile(files) { console.log('upload files', files) console.log('upload files', files) // 文件上传的函数,返回一个promise return new Promise((resolve, reject) => { const tempFilePaths = files.tempFilePaths; //上传返回值 const that = this; const object = {}; for (var i = 0; i < tempFilePaths.length; i++) { let filePath = '',cloudPath = '' filePath = tempFilePaths[i] // 上传图片 // cloudPath 最好按工夫 遍历的index来排序,防止文件名反复 cloudPath = 'blog-title-image-' + new Date().getTime() + '-' + i + filePath.match(/\.[^.]+?$/)[0] console.log(filePath) console.log(cloudPath) const upload_task = wx.cloud.uploadFile({ filePath, cloudPath, success: function(res) { console.log(res) // 可能会有好几个200+的返回码,示意胜利 if (res.statusCode === 200 || res.statusCode === 204 || res.statusCode === 205) { const url = res.fileID that.data.files.push(url) if (that.data.files.length === tempFilePaths.length) { object.urls = that.data.files; resolve(object) //这就是判断是不是最初一张曾经上传了,用来返回, } } else { reject('error') } }, fail: function(err) { console.log(err) }, conplete: () => { } }) } }) // 文件上传的函数,返回一个promise},uploadError(e) { console.log('upload error', e.detail)},uploadSuccess(e) { console.log('upload success', e.detail)}});
属性参考文档:https://wechat-miniprogram.gi...
咱们关联云开发之后,咱们即可将照片上传到数据库中。
为方便管理,咱们能够创立CMS内容管理器。
创立CMS内容管理器
点击云开发->更多->内容治理 进行开明。
2.云开发为大家筹备了根底版,为大家提供了肯定的收费额度。
设置管理员账号以及明码,舒适提醒明码请牢记(如果遗记明码能够再内容管理器页面重置明码),设置实现后急躁期待零碎初始化。
3.依据页面中提供的拜访地址拜访页面登陆后,创立新的我的项目(这里以花园假期为例)
4.咱们在内容模型中创立照片上传治理(这里模仿状况为仅须要用户上传和记录用户id)
创立内容模型
如果须要用户上传多张照片,在设置照片字段时候须要勾选容许用户上传多张照片!
5.用户上传后咱们能够再内容汇合,相应模型中查看。
成果展现
本文由博客一文多发平台 OpenWrite 公布!