微信小程序上传一或多张图片

微信小程序上传一或多张图片

一.要点

1.选取图片

       
       
  1. wx.chooseImage({
  2. sizeType: [], // original 原图,compressed 压缩图,默认二者都有
  3. sourceType: [], // album 从相册选图,camera 使用相机,默认二者都有
  4. success: function (res) {
  5. console.log(res);
  6. var array = res.tempFilePaths, //图片的本地文件路径列表
  7. }
  8. })

2.上传图片

       
       
  1. wx.uploadFile({
  2. url: '', //开发者服务器的 url
  3. filePath: '', // 要上传文件资源的路径 String类型!!!
  4. name: 'uploadFile', // 文件对应的 key ,(后台接口规定的关于图片的请求参数)
  5. header: {
  6. 'content-type': 'multipart/form-data'
  7. }, // 设置请求的 header
  8. formData: { }, // HTTP 请求中其他额外的参数
  9. success: function (res) {
  10. },
  11. fail: function (res) {
  12. }
  13. })

二.代码示例

       
       
  1. // 点击上传图片
  2. upShopLogo: function () {
  3. var that = this;
  4. wx.showActionSheet({
  5. itemList: ['从相册中选择', '拍照'],
  6. itemColor: "#f7982a",
  7. success: function (res) {
  8. if (!res.cancel) {
  9. if (res.tapIndex == 0) {
  10. that.chooseWxImageShop('album')
  11. } else if (res.tapIndex == 1) {
  12. that.chooseWxImageShop('camera')
  13. }
  14. }
  15. }
  16. })
  17. },
  18. chooseWxImageShop: function (type) {
  19. var that = this;
  20. wx.chooseImage({
  21. sizeType: ['original', 'compressed'],
  22. sourceType: [type],
  23. success: function (res) {
  24. /*上传单张
  25. that.data.orderDetail.shopImage = res.tempFilePaths[0],
  26. that.upload_file(API_URL + 'shop/shopIcon', res.tempFilePaths[0])
  27. */
  28. /*上传多张(遍历数组,一次传一张)
  29. for (var index in res.tempFilePaths) {
  30. that.upload_file(API_URL + 'shop/shopImage', res.tempFilePaths[index])
  31. }
  32. */
  33. }
  34. })
  35. },
  36. upload_file: function (url, filePath) {
  37. var that = this;
  38. wx.uploadFile({
  39. url: url,
  40. filePath: filePath,
  41. name: 'uploadFile',
  42. header: {
  43. 'content-type': 'multipart/form-data'
  44. }, // 设置请求的 header
  45. formData: { 'shopId': wx.getStorageSync('shopId') }, // HTTP 请求中其他额外的 form data
  46. success: function (res) {
  47. wx.showToast({
  48. title: "图片修改成功",
  49. icon: 'success',
  50. duration: 700
  51. })
  52. },
  53. fail: function (res) {
  54. }
  55. })
  56. },
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值