1. 程式人生 > >小程式上傳wx.uploadFile - 小程式請假-請求

小程式上傳wx.uploadFile - 小程式請假-請求

小程式上傳wx.uploadFile

UploadTask wx.uploadFile(Object object)
將本地資源上傳到伺服器。客戶端發起一個 HTTPS POST 請求,其中 content-type 為 multipart/form-data。使用前請注意閱讀相關說明。

num=1;當num==3時,設定按鈕隱藏
直接上程式碼:

在這裡插入圖片描述

<view class='uploader' wx:for="{{files}}" wx:key="{{index}}">
  <image src='../../img/cha.png' class='cha' catchtap='delete' data-index="{{index}}"></image>
  <image src='{{item}}' class='upload-img'></image>
</view>
<view class='uploader' wx:if="{{upload}}" bindtap="previewImage">
  <view class='uploader-content'>
    <view class='add-icon'>+</view>
    <view class='title'>新增圖片</view>
  </view>
</view>
  <button bindtap='delete'>刪除</button>
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    upload: true,
    files: [],
    sum: 0,
  },
  //  上傳圖片
  previewImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
      success: (res) => {
        console.log(res) // 列印輸出返回值
        let files = this.data.files
        files.push(res.tempFilePaths[0]) // 把圖片地址push到陣列中
        let sum = this.data.sum
        sum++ // 開始計數
        this.setData({
          sum: sum
        })
        if (this.data.sum == 3) { // 如果sum==3隱藏上傳按鈕
          this.setData({
            upload: false
          })
        }
        // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
        this.setData({
          files: files
        });

      }
    })
  },

  // 刪除圖片
  delete: function(e) {
    let index = e.currentTarget.dataset.index
    let files = this.data.files
    files.splice(index, 1)
    this.setData({
      files: files
    })
    if (this.data.files.length == 0) {
      this.setData({
        upload: true,
        sum: 0
      })
    }
  }
})
.uploader{
position: relative;
width: 175rpx;
height: 175rpx;
background: #F0F0F2;
margin-top:50rpx;
border-radius:10rpx;
float: left;
margin-right:20rpx;
}
.add-icon{
position: absolute;
font-size:105rpx;
top:-23rpx;
left:50rpx;
color: #A3A3A3;
}
.title{
position:absolute;
bottom:30rpx;
left:32rpx;
color:#A3A3A3;
font-size:31rpx;

}
.upload-img{
width: 100%;
height: 100%;
border-radius: 8rpx;
}
.cha{
z-index:3;
width:30rpx;
height:30rpx;
position:absolute;
right:0;

}

上傳圖片:

<form bindsubmit="formSubmit" id='2' bindreset="formReset">  
<input style='display:none' name='program_id' value='{{program_id}}'></input>  
      <view class='caigou_centent'>描述說明(選填)</view>  
      <textarea class='textarea' placeholder="" name="content" value='{{formdata}}' />  
  
      <view class="big-logos">  
        <image bindtap="upimg" src='../../images/jia.png'></image>  
        <block wx:for="{{img_arr}}">  
          <view class='logoinfo'>  
            <image src='{{item}}'></image>  
          </view>  
        </block>  
      </view>  
      <button class='btn' formType="submit">釋出</button>  
</form>  
var adds = {};  
Page({  
  data: {  
img_arr: [],  
formdata: '',  
},  
  formSubmit: function (e) {  
    var id = e.target.id  
    adds = e.detail.value;   
    adds.program_id = app.jtappid  
    adds.openid = app._openid  
    adds.zx_info_id = this.data.zx_info_id  
    this.upload()  
  },  
  
  upload: function () {  
    var that = this  
      for (var i=0; i < this.data.img_arr.length; i++) {  
        wx.uploadFile({  
          url: 'https:***/submit',  
          filePath: that.data.img_arr[i],  
          name: 'content',  
          formData: adds,   
          success: function (res) {  
            console.log(res)  
            if (res) {  
              wx.showToast({  
                title: '已提交發布!',  
                duration: 3000  
              });  
            }  
          }  
        })  
      }  
      this.setData({  
        formdata: ''  
      })  
  },  
  upimg: function () {  
    var that = this;  
    if (this.data.img_arr.length<3){  
    wx.chooseImage({  
      sizeType: ['original', 'compressed'],  
      success: function (res) {  
        that.setData({  
          img_arr: that.data.img_arr.concat(res.tempFilePaths)  
        })  
      }  
    })  
    }else{  
      wx.showToast({  
        title: '最多上傳三張圖片',  
        icon: 'loading',  
        duration: 3000  
      });  
    }  
  },  
  })

上傳檔案

<button bindtap="upload">上傳檔案</button>
Page({
  data: {
    path: ''
  },
  upload: function() {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        wx.uploadFile({
          url: 'http://example.weixin.qq.com/upload',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success: function(res) {
            var data = res.data
            wx.showModal({
              title: '上傳檔案返回狀態',
              content: '成功',
              success: function(res) {
                if (res.confirm) {
                  console.log('使用者點選確定')
                }
              }
            }) //do something
          },
          fail: function(res) {
            console.log(res)
          }
        })
        that.setData({
          path: tempFilePaths
        })
      }
    })
  }
})

url string
開發者伺服器地址

filePath string
要上傳檔案資源的路徑

name string
檔案對應的 key,開發者在服務端可以通過這個 key 獲取檔案的二進位制內容

header
HTTP 請求 Header,Header 中不能設定 Referer

formData
HTTP 請求中其他額外的 form data

success
介面呼叫成功的回撥函式

fail介面呼叫失敗的回撥函式

complete
介面呼叫結束的回撥函式(呼叫成功、失敗都會執行)

示例程式碼
wx.chooseImage({
  success (res) {
    const tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'https://example.weixin.qq.com/upload', //僅為示例,非真實的介面地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success (res){
        const data = res.data
        //do something
      }
    })
  }
})

GET請求

wx.request({  
    url: 'https://URL',  //這裡''裡面填寫你的伺服器API介面的路徑  
    data: {},  //這裡是可以填寫伺服器需要的引數  
    method: 'GET', // 宣告GET請求  
    // header: {}, // 設定請求的 header,GET請求可以不填  
    success: function(res){  
console.log("返回成功的資料:" + res.data ) //返回的會是物件,可以用JSON轉字串打印出來方便檢視資料  
console.log("返回成功的資料:"+ JSON.stringify(res.data)) //這樣就可以愉快的看到後臺的資料啦  
    },  
    fail: function(fail) {  
      // 這裡是失敗的回撥,取值方法同上,把res改一下就行了  
    },  
    complete: function(arr) {  
      // 這裡是請求以後返回的所以資訊,請求方法同上,把res改一下就行了  
    }  
  })  

POST請求

   var that = this //建立一個名為that的變數來儲存this當前的值  
   wx.request({  
      url: '',  
      method: 'post',  
      data: {  
        openid: 'openid'  //這裡是傳送給伺服器的引數(引數名:引數值)  
      },  
      header: {  
        'content-type': 'application/x-www-form-urlencoded'  //這裡注意POST請求content-type是小寫,大寫會報錯  
      },  
      success: function (res) {  
        that.setData({ //這裡是修改data的值  
          test: res.data //test等於伺服器返回來的資料  
        });  
        console.log(res.data)  
      }  
  });  

小程式請假

<view class="head">
  <view class="head_item {{selected?'head_itemActive':''}}" bindtap="selected">新請假</view>
  <view class="ring"></view>
  <view class="head_item {{selected1?'head_itemActive':''}}" bindtap='selected1'>請假結果</view>
</view>
<view class="main {{selected?'show':'hidden'}}">
  <form bindsubmit="formSubmit" bindreset="formReset">
    <view class='item'>
      \r\n\r\n\r\n\r\n\r\n\r\n年級:
      <view class='bk'>
        <input name='nickname' class="textarea" placeholder="{{geren.nickname}}" value='{{geren.nickname}}' bindinput="nickname" maxlength='15' auto-height/>
      </view>
    </view>
    <view class='item'>
      \r\n\r\n\r\n\r\n\r\n\r\n班級:
      <view class='bk'>
        <input name='nickname' class="textarea" placeholder="{{geren.nickname}}" value='{{geren.nickname}}' bindinput="nickname" maxlength='15' auto-height/>
      </view>
    </view>
    <view class='item'>
      \r\n\r\n\r\n\r\n\r\n\r\n學號:
      <view class='bk'>
        <input name='realName' class="textarea" placeholder="{{detailgeren.realName}}" value='{{detailgeren.realName}}' bindinput="realName" maxlength='15' auto-height/>
      </view>
    </view>
    <view class='item'>
      申請姓名:
      <view class='bk'>
        <input name='realName' class="textarea" placeholder="{{detailgeren.realName}}" value='{{detailgeren.realName}}' bindinput="realName" maxlength='15' auto-height/>
      </view>
    </view>
    <view class='item'>
      請假天數:
      <view class='bk'>
        <input name='realName' class="textarea" placeholder="{{detailgeren.realName}}" value='{{detailgeren.realName}}' bindinput="realName" maxlength='15' auto-height/>
      </view>
    </view>
    <view class='item'>
      開始時間:
      <view class='bk'>
        <view class='time'>
          <picker mode="date" value="{{date}}" start="2018-01-01" end="2222-10-08" bindchange="changeDate" name="starttime" bindchange="changeDate">
            <view>
              {{date}}
            </view>
          </picker>
        </view>
      </view>
    </view>
    <view class='item'>
      結束時間:
      <view class='bk'>
        <view class='time'>
          <picker mode="date" value="{{date1}}" start="2018-11-11" end="2222-01-01" bindchange="changeDate1" name="endtime">
            <view>
              {{date1}}
            </view>
          </picker>
        </view>
      </view>
    </view>
    <view class='item'>
      請假型別:
      <view class='bk'>
        <input name='realName' class="textarea" placeholder="{{detailgeren.realName}}" value='{{detailgeren.realName}}' bindinput="realName" maxlength='15' auto-height/>
      </view>
    </view>
    <view class='item'>
      請假原因:
      <view class='bk'>
        <input name="detailAddress" class="textarea" placeholder="{{detailgeren.detailAddress}}" value='{{detailgeren.detailAddress}}' bindinput="detailAddress" maxlength='100' auto-height/>
      </view>
    </view>
    <view class='anniu'>
      <button class='btn' formType="submit">提交</button>
    </view>
  </form>
</view>
Page {
  background-color: #f1f1f1;
}


/* 新請假 */

.item {
  display: flex;
  flex-direction: row;
  font-size: 30rpx;
  color: #acacac;
  margin: 25rpx;
  align-items: center;
}

.btn {
  background-color: #79caff;
  color: #fff;
  width: 150rpx;
  font-size: 30rpx;
  margin-top: 30rpx;
}

.bk {
  border-radius: 10rpx;
  border: 2rpx solid #ccc;
  padding: 10rpx;
  width: 65%;
}

.textarea {
  width: 100%;
}