這篇文章主要介紹了微信小程序 拍照或從相冊選取圖片上傳代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
upload.wxml
<!--pages/upload/upload.wxml--><button bindtap='uploadPhoto'>拍照選取照片上傳</button>
upload.js
// pages/upload/upload.jsPage({ data: {  imgData: [] }, uploadPhoto(e) { // 拍攝或從相冊選取上傳  let that = this;  wx.chooseImage({   count: 1, // 默認9   sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有   sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有   success(res) {    let tempFilePaths = res.tempFilePaths; // 返回選定照片的本地路徑列表     that.upload(that, tempFilePaths);   }  }) }, upload(page, path) { // 上傳圖片  wx.showToast({ icon: "loading", title: "正在上傳……" });  wx.uploadFile({   url: '上傳圖片接口url', //后端接口   filePath: path[0],   name: 'file',   header: {    "Content-Type": "multipart/form-data"   },   success(res) {    if (res.statusCode != 200) {     wx.showModal({ title: '提示', content: '上傳失敗', showCancel: false });     return;    } else{     console.log("上傳成功! 可對返回的值進行操作,比如:存入imgData;");    }   },   fail(e) {    wx.showModal({ title: '提示', content: '上傳失敗', showCancel: false });   },   complete() {    wx.hideToast(); //隱藏Toast   }  }) }})ps:以上是單圖上傳,如果需要多圖上傳,請看下方:
// pages/publish/publish.jsPage({ data: {  imgData: [] }, uploadPhoto(e) { // 拍攝或從相冊選取上傳  let that = this;  wx.chooseImage({   count: 9 - that.data.imgData.length, // 默認最多上傳9張   sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有   sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有   success(res) {    let tempFilePaths = res.tempFilePaths; // 返回選定照片的本地路徑列表     that.upload(that, tempFilePaths);   }  }) }, upload(page, path) { // 上傳圖片  let that = this;  wx.showToast({ icon: "loading", title: "正在上傳……" });  for (var i=0; i<path.length; i++) {   wx.uploadFile({    url: '上傳圖片接口url', //后端接口    filePath: path[i],    name: 'file',    header: app.globalData.header,    success(res) {     if (res.statusCode != 200) {      wx.showModal({       title: '提示',        content: '第' + i +'張圖片上傳失敗',        showCancel: false      });      return;     } else {      console.log('第' + i +'張圖片上傳成功!可在此操作,比如:存入imgData;');     }    },    fail(e) {     wx.showModal({     title: '提示',      content: '第' + i +'張圖片上傳失敗',      showCancel: false     });    },    complete() {     wx.hideToast(); //隱藏Toast    }   })  } }})以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答