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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章