1. 程式人生 > 實用技巧 >微信小程式OSS上傳圖片

微信小程式OSS上傳圖片

<!--pages/homework/index.wxml-->
<wxs module="m1">
    function fn(arr, arg) {
        var result = {
            indexOf: false,
            toString: ''
        }
        result.indexOf = arr.indexOf(arg) > -1;
        result.toString = arr.join(",");
        return result;
    }
    module.exports.fn = fn;
</wxs> <view class="homeworkpage"> <view class="h-header"> <view class="title">{{homeworkinfo.assignmentName}}</view> <view class="pjname">{{homeworkinfo.projectName}}</view> <view class="time"> <image src="/images/homework/timeclock.png"
></image> <text>截止時間</text> <text class="timebox">{{fininshtime}}</text> </view> <view class="work-info"> <text>上傳次數 {{homeworkinfo.count}}</text> <text>合格分 {{homeworkinfo.passScore}}</
text> </view> </view> <!-- 作業要求 --> <view class="h-mid"> <text class="title">作業要求</text> <image src="/images/course/pickdown.png" class="arrow" wx:if="{{arrowup==1}}" bindtap="arrowtap"></image> <image src="/images/course/pickup.png" class="arrow" wx:else bindtap="arrowtap"></image> <view class="content" wx:if="{{arrowup==1}}"> <text>{{homeworkinfo.assignmentContent}}</text> <view wx:for="{{homeworkinfo.fileList}}" class="homework-filelist"> <image src="{{item.ossUrl}}" wx:if="{{m1.fn(uptypeListpic,item.suffix).indexOf}}" mode="widthFix"></image> <video src="{{item.ossUrl}}" wx:if="{{m1.fn(uptypeList,item.suffix).indexOf}}"></video> </view> </view> </view> <!-- 沒有機會提交了 --> <view class="noOpoCommit" wx:if="{{(homeworkinfo.finishTime<nowtime)&&(homeworkinfo.amendable==0)}}"> <view> <image src="/images/homework/book.png"></image> </view> <text>下次記得按時提交哦</text> </view> <!-- 提交作業 --> <view class="h-foot" wx:if="{{homeworkinfo.finishTime>nowtime||homeworkinfo.amendable}}"> <view class="title">提交作業</view> <view class="box"> <textarea class="text" placeholder="文字說明...({{homeworkinfo.answerCharaterNumMax}}字以內)" maxlength="{{homeworkinfo.answerCharaterNumMax}}" bindinput="worktextchange" value="{{wordinfo}}"></textarea> <text class="textnumber">{{writenum}}/{{homeworkinfo.answerCharaterNumMax}}</text> </view> <view class="uploadList"> <view class="uploadItem {{item.isTouchMove ? 'touch-move-active' : ''}}" wx:for="{{filevolistshow}}" data-index="{{index}}" bindtouchstart="touchstart" bindtouchmove="touchmove"> <view class="uploadItem-content"> <view class="item-image"> <image src="{{item.filePath}}"></image> </view> <view class="item-right-box"> <view class="item-filename">{{item.fileName}}</view> <progress percent="{{item.uploadProgress}}" active stroke-width="3" duration="1" wx:if="{{item.uploadSuccess==0}}" bindactiveend="uploadEnd" /> <text class="uploading-text" wx:if="{{item.uploadSuccess==0}}">上傳中</text> <text class="uploadsuccess-text" wx:if="{{item.uploadSuccess}}">上傳成功</text> <text class="uploading-size">{{item.size}}</text> </view> </view> <view class="uploadItem-del" catchtap="uploadItemdel" data-index="{{index}}"> <image src="/images/homework/delfile.png"></image> </view> </view> <view class="delAllFile" wx:if="{{filevolistshow.length>0}}" bindtap="delAllList"> <image src="/images/homework/delAll.png"></image> <text>全部刪除</text> </view> </view> <view class="add-btn-list"> <view class="add-file" bindtap="addfiletap" data-type="0" id="add-file"> <view class="heng"></view> <view class="shu"></view> </view> </view> <view class="uptips"> 點選“+”新增圖片、視訊、音訊,每個檔案最大為50M,每次最多上傳{{homeworkinfo.answerAttachmentNumMax}}個 </view> <view class="submit" id="submitfile" bindtap="submithomework">提交</view> </view> </view>
// pages/homework/index.js
//獲取應用例項
const app = getApp()
const publicApi = require('../../../commen/api.js');
const requestApi = require('../../../commen/requestApi.js') //引入util.js,地址根據自己的地址填寫;
const router = require('../../../router/index.js');
var util = require("../../../utils/util.js");
let uptypeList=["mp3","mp4","avi","wav","rmvb","png","jpg","jpeg","gif"]
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    assignmentId: '',
    writenum: 0,
    arrowup: 1,
    homeworkinfo: '',
    fininshtime: '',
    wordinfo: '',
    ossData: '',
    filevoslist: [],
    filevolistshow:[],
    uploadProgress: '',
    uploadSuccess:0,
    nowtime:new Date().getTime(),
    uptypeList:["mp4","avi","wav","rmvb"],
    uptypeListpic:[".png",".jpg","jpeg","gif"]
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {
    var params = JSON.parse(decodeURIComponent(options.encodedData));

    this.setData({
      assignmentId: params.homeid
    })
    this.gethomeworkinfo();
  },

  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {

  },
  gethomeworkinfo: function () {
    var that = this;
    app.requestByGet(
      publicApi.getHomeworkDetail, {
        assignmentId: this.data.assignmentId
      },
      (res => {
        if (res.data.code == "1000") {
          var ft = util.formatTimeTwo(res.data.data.finishTime, "Y-M-D h:m:s");
          if (new Date(ft) > new Date("2025-01-01 00:00:00")) {
            ft = "長期有效"
          }
          that.setData({
            homeworkinfo: res.data.data,
            fininshtime: ft
          })
        }
      })

    )

  },
  arrowtap: function () {
    this.data.arrowup = !this.data.arrowup;
    this.setData({
      arrowup: this.data.arrowup
    })

  },
  worktextchange: function (e) {
    console.log(e.detail.value.length)
    this.data.writenum = e.detail.value.length;
    this.setData({
      writenum: this.data.writenum,
      wordinfo: e.detail.value
    })
  },
  beforeUpload: function () {},
  progressFunc: function () {},
  completeFunc: function () {},
//手指觸控動作開始 記錄起點X座標
touchstart: function (e) {
  //開始觸控時 重置所有刪除
  this.data.filevolistshow.forEach(function (v, i) {
   if (v.isTouchMove)//只操作為true的
    v.isTouchMove = false;
  })
  this.setData({
   startX: e.changedTouches[0].clientX,
   startY: e.changedTouches[0].clientY,
   filevolistshow: this.data.filevolistshow
  })
 },
 //滑動事件處理
 touchmove: function (e) {
  var that = this,
   index = e.currentTarget.dataset.index,//當前索引
   startX = that.data.startX,//開始X座標
   startY = that.data.startY,//開始Y座標
   touchMoveX = e.changedTouches[0].clientX,//滑動變化座標
   touchMoveY = e.changedTouches[0].clientY,//滑動變化座標
   //獲取滑動角度
   angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
  that.data.filevolistshow.forEach(function (v, i) {
   v.isTouchMove = false
   //滑動超過30度角 return
   if (Math.abs(angle) > 30) return;
   if (i == index) {
    if (touchMoveX > startX) //右滑
     v.isTouchMove = false
    else //左滑
     v.isTouchMove = true
   }
  })
  //更新資料
  that.setData({
    filevolistshow: that.data.filevolistshow
  })
 },
 /**
  * 計算滑動角度
  * @param {Object} start 起點座標
  * @param {Object} end 終點座標
  */
 angle: function (start, end) {
  var _X = end.X - start.X,
   _Y = end.Y - start.Y
  //返回角度 /Math.atan()返回數字的反正切值
  return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
 },
 //刪除事件
 uploadItemdel: function (e) {
  this.data.filevolistshow.splice(e.currentTarget.dataset.index, 1);
  this.data.filevoslist.splice(e.currentTarget.dataset.index, 1);
  
  this.setData({
    filevolistshow: this.data.filevolistshow,
    filevoslist:this.data.filevoslist
  })
 },
 delAllList:function(){
  this.setData({
    filevolistshow: [],
    filevoslist:[]
  })
 },
 //ossData
  addfiletap: function (e) {
    var id= e.currentTarget.dataset.type;
    if(this.data.filevoslist.length>=this.data.homeworkinfo.answerAttachmentNumMax){
      wx.showToast({
        title: '檔案個數已達上限!',
        icon:"none",
        duration:2000
      })
      return;
    }

    app.requestByGet(
      publicApi.aliyunUpload, {
        needTranscode: true,
        type: 2
      }, (res => {
        this.setData({
          ossData:res.data.data
        })
        this.beginUpload(id);
      })
    )


  },


  resultItemName(name) {
    let nameArr = name.split(".");
    let onlyNameArr = nameArr.filter((item, index) => {
      return index < nameArr.length - 1;
    });
    let onlyNameStr = onlyNameArr.join(".");
    if (onlyNameStr.length > 10) {
      return onlyNameStr.slice(0, 10) + "..." + nameArr[nameArr.length - 1];
    } else {
      return name;
    }
  },
  itemFileSize(size) {
    if (size < 1024) {
      return size + "B"
    } else if (size < 1048576) {
      return (size / 1024).toFixed(2) + "KB"
    } else {
      return (size / 1048576).toFixed(2) + "M"
    }
  },
  chooseImgfile(){
    var that = this;
    // wx.chooseImage({
    //   count: 1, // 最多可以選擇的圖片張數,預設9
    //   sizeType: ['original', 'compressed'], // original 原圖,compressed 壓縮圖,預設二者都有
    //   sourceType: ['album', 'camera'], // album 從相簿選圖,camera 使用相機,預設二者都有
    //   success: function(res){ 

    //     console.log(res);
    //     that.uploadTask(res);      
       
    //   },
    //   fail: function() {
    //    wx.showToast({
    //      title: 'fail',
    //    })
    //   },
    //   complete: function() {
       
    //   }
    // })
    wx.chooseMedia({
      count: 1,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration:60,
      camera: 'back',
      success(res) {
        console.log(res.tempFiles.tempFilePath)
        console.log(res.tempFiles.size)
        that.uploadTask(res);    
      }
    })
  },
  chooseVideoFile(){
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        console.log(res)
      },
      fail(){console.log("errror")}
    })
  },

  //開始上傳檔案
  beginUpload: function (type) {
    this.setData({
      uploadProgress:0,
      uploadSuccess:0
    })

    this.chooseImgfile()
  
},
  uploadTask(res){

    var param = JSON.parse(this.data.ossData);
    var that = this;
    var filevolist = this.data.filevoslist;
    var filevolistshow =this.data.filevolistshow;
    console.log(param)

     var filesize = that.itemFileSize(res.tempFiles[0].size);
        var tempFilePaths = res.tempFiles[0].tempFilePath;
        var tempFiletype = tempFilePaths.split(".")[tempFilePaths.split(".").length - 1];
        var tempFilename = '附件'+(filevolist.length+1)+'.'+tempFiletype;

        console.log(tempFiletype) 

        console.log(res)

        var osstempFilename = requestApi.random_fileName(30) + '.' + tempFiletype;
        var fileinfo = {
          fileName: tempFilename,
          ossUrl: param.host + "/"+ param.dir + "/"+ osstempFilename,              
          size: filesize,         
          suffix: '.' + tempFiletype,
          statusCode: "success"
        }
        
        var fileinfoShow= {
          fileName:that.resultItemName(tempFilename),
          filePath:"",
          size: filesize,
          suffix: '.' + tempFiletype,
          uploadProgress:0,
          uploadSuccess:0,
          isTouchMove:false
        };
        if(that.data.uptypeList.indexOf(tempFiletype)>-1){
          fileinfoShow.filePath = res.tempFiles[0].thumbTempFilePath
        }
        else{
          fileinfoShow.filePath = tempFilePaths
        }
       
        //頁面顯示 檔案資訊
        filevolist.push(fileinfo);
        filevolistshow.push(fileinfoShow);
        that.setData({
          filevoslist:filevolist,
          filevolistshow:filevolistshow         
        })

        console.log(that.data.filevoslist)
        if (filesize / 1024 > 51200) {
          wx.showToast({
            title: '檔案不能大於50M',
            duration: 1000
          })
          return;
        }

        var filedata = {
          'name': osstempFilename,
          'Filename': param.dir + "/" + osstempFilename,
          'key': param.dir + "/" + osstempFilename,
          'policy': param.policy,
          'OSSAccessKeyId': param.accessid,
          'success_action_status': "200",
          'signature': param.signature,

        };

        console.log(filedata)


        var uploadTask = wx.uploadFile({
          url: param.host,
          header: {
            'content-type': 'multipart/form-data'
          },
          formData: filedata,
          filePath: tempFilePaths,
          name: 'file',
          success: function (res) {
            //進度變100
            var info = that.data.filevolistshow;
            info[info.length-1].uploadProgress=100;
            that.setData({
              filevolistshow:info 
            })         
            wx.showToast({
              title: "上傳成功",
              icon: 'success',
              duration: 1000
            })
          },
          fail: function ({
            errMsg
          }) {
            console.log('upladImage fail, errMsg is: ', errMsg)
            wx.showToast({
              title: "上傳失敗",
              duration: 1000
            })
          },
        })
        uploadTask.onProgressUpdate((res) => {

          console.log('上傳進度', res.progress + " " + new Date());
          
        })

  },
  uploadEnd(){
    //上傳成功標誌置1
    var info = this.data.filevolistshow;
    info[info.length-1].uploadSuccess=1;
    this.setData({
      filevolistshow:info 
    })
    console.log(info)
  },
  //提交作業
  submithomework: function () {
    var that = this;
     
    if(that.data.filevoslist.length==0&&that.data.wordinfo.length==0){
      wx.showToast({
        title: '您未填寫內容或上傳任何內容',
        icon:"none",
        duration:2000
      })
      return;
    }

    app.requestByPost(
      publicApi.submitHomework, {
        assignmentId: this.data.assignmentId,
        source: 1,
        fileVos: that.data.filevoslist,
        content: that.data.wordinfo
      }, (res => {
           wx.showToast({
             title: '提交成功',
           })
           router.push({
             name:"homeworkSubResDir",
             data:{
              homeid:that.data.assignmentId
             }
           })
      })
    )

  },
  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {

  },

  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {

  },

  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {

  },

  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {

  }
})