微信小程序-拍照或选择图片并上传文件
2019/6/27 21:30:27
本文主要是介绍微信小程序-拍照或选择图片并上传文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
微信小程序-拍照或选择图片并上传文件
调用拍照API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/media-picture.html?t=20161222#wxchooseimageobject
上传文件API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-file.html
主要js代码:
choice: function () { var that = this wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths that.setData({ textHidden: true, image_photo: tempFilePaths, photoHidden: false }) } }) }, uploadPhoto: function () { var that = this let param = util.json2Form({ tel: '18600346580', orderSn: that.data.orderSn, parkingPhoto: that.data.image_photo, }); wx.uploadFile({ url: 'https://testapi.****.com/v4.0.0/uploadParkingPhoto', //仅为示例 filePath: that.data.image_photo[0], name: 'parkingPhoto', formData: { 'tel': '***********', 'orderSn': that.data.orderSn, }, success: function (res) { var obj = JSON.parse(res.data);; console.log(obj.result) console.log(obj.msg) var resule = obj.result; var msg = obj.msg; if (resule == 'false') { wx.showToast({ title: msg, icon: 'success', duration: 2000 }) } else { wx.navigateBack({ delta: 1, success: function (res) { wx.showToast({ title: msg, icon: 'success', duration: 2000 }) }, }) } } }) }
Tip:
1.调用wx.chooseImage() 自动弹出选择窗口,不用调用操作菜单wx.showActionSheet(),否则重复
如图
2. 上传文件的时候filePath必须是数组,当你单张的时候需要使用数组,若只有一张要用[0]
3. 最需要注意的是,success返回数据是String类型,我们需要将String类型转换成Object
js字符串转换成obj
用js 是有三种方法的
- js自带的eval函数,其中需要添加小括号eval('('+str+')');
- JSON.parse(str)
- $.parseJSON( jsonstr )
但是在微信小程序中,我们只能用JSON.parse(str),其他的都不可以
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
这篇关于微信小程序-拍照或选择图片并上传文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南