1. 程式人生 > >MVC Api微信小程式wx.uploadFile上傳檔案,前後端程式碼例項

MVC Api微信小程式wx.uploadFile上傳檔案,前後端程式碼例項

// 小程式端js
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    userHeaderImage: "../../../images/1.jpg"
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function(options) {

  },

  chooseImage: function() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作為img標籤的src屬性顯示圖片
        const tempFilePaths = res.tempFilePaths[0]
        that.setData({
          userHeaderImage: tempFilePaths
        })
        console.log(tempFilePaths)
        //上傳圖片
        wx.uploadFile({
          url: 'https://xxxx/api/wxtest/uploadfile', //僅為示例,非真實的介面地址
          filePath: tempFilePaths,
          name: 'file',
          // header: {
          //   "content-type": "multipart/form-data",
          //   'content-type': 'application/x-www-form-urlencoded' //表單提交
          // },
          formData: {
            'userId': 10001
          },
          success(res) {
            const data = res.data
            console.log(res);
            //do something
          }
        })
      }
    })
  },
})
index.wxml
<view class='mainView' bindtap='chooseImage'>
  <image class="imageClass" src="{{userHeaderImage}}"></image>
</view>
        #region 測試微信小程式圖片上傳
        [Route("api/wxtest/uploadfile")] //設定路由
        [HttpPost]
        public HttpResponseMessage WxPostFile()
        {
            //定義
            ResponseResult obj = new ResponseResult();
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files[0];
                var userId = HttpContext.Current.Request["userId"];
                var path = "/upload/";
                var mapPath = HttpContext.Current.Server.MapPath(path); //硬碟物理目錄
                var fileName = Until.GetNowTimeString();
                var fileExt = Path.GetExtension(file.FileName);
                var mapPathFullPath = mapPath + fileName + fileExt; //硬碟物理路徑
                var siteFullPath = path + fileName + fileExt; //網站路徑
                if (!Directory.Exists(mapPath))
                {
                    Directory.CreateDirectory(mapPath);
                }
                file.SaveAs(mapPathFullPath);
                obj.status = true;
                obj.message = siteFullPath;
                obj.info = userId;
            }
            catch (Exception ex)
            {
                obj.status = false;
                obj.message = ex.Message;
            }
            var resultObj = JsonConvert.SerializeObject(obj);
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(resultObj, Encoding.GetEncoding("UTF-8"), "application/json")
            };
            return result;
        }
        #endregion