微信小程序之本地上传图片

时间:2024-10-03 13:34:50
  • //上传
  • function upload(that, id) {
  • if (that.data.imageList.length == 0) {
  • return;
  • }
  • wx.uploadFile({
  • url: '....', //仅为示例,非真实的接口地址
  • filePath: that.data.imageList[0],
  • name: 'file',
  • formData: {
  • 'id': id
  • },
  • success: function (res) {
  • var data = res.data
  • console.log(data);
  • var json = JSON.parse(res.data); //
  • wx.showToast({
  • title: json.msg,
  • icon: 'none',
  • duration: 3000
  • })
  • }
  • })
  • }
  • Page({
  • data: {
  • student: null,
  • imageList: []
  • },
  • formSubmit: function (e) {
  • console.log(e.detail.value);
  • wx.request({
  • url: '....',//仅为示例,非真实的接口地址
  • method: 'POST',
  • data: e.detail.value,
  • header: {
  • 'content-type': 'application/x-www-form-urlencoded'
  • },
  • success: (res) => {
  • console.log(res);
  • if (res.error) {
  • wx.showToast({
  • title: res.data.msg,
  • icon: 'none',
  • duration: 2000
  • })
  • } else {
  • //上传照片
  • upload(this, res.data.id);
  • wx.showToast({
  • title: '添加成功',
  • icon: 'success',
  • duration: 2000,
  • success: function () {
  • setTimeout(function () {
  • wx.navigateTo({
  • url: '../index/index',
  • })
  • }, 2000)
  • }
  • })
  • }
  • }
  • })
  • },
  • chooseImage: function () {
  • var that = this
  • wx.chooseImage({
  • sourceType: ['album', 'camera'],
  • sizeType: ['original', 'compressed'],
  • count: 1,
  • success: function (res) {
  • console.log(res)
  • that.setData({
  • imageList: res.tempFilePaths
  • })
  • }
  • })
  • },
  • previewImage: function (e) {
  • var current = e.target.dataset.src
  • wx.previewImage({
  • current: current,
  • urls: this.data.imageList
  • })
  • }
  • })