小程序上传图片(.net core 接口)

小程序页面

<view wx:if="{{tempFilePath}}" class="choose-pic" bindtap="openModalPic">
  {{tempFilePath?'重新选择图片':'选择图片'}}
view>

<view wx:else class="upload-pic-btn">
  <image src="{{upload_btn_pic}}" bindtap="openModalPic">image>
view>

<view class="pre-view-image" hidden="{{!tempFilePath}}">
  <image src="{{tempFilePath}}" bindtap="preView">image>
view>

<view class="image-size" hidden="{{!tempFilePath||is_update_pic}}">
  <view class="image-size-title">
    图片大小:
  view>
  <view class="image-size-value ">
    {{size_unit_m}}M
  view>
view>

<view class=" {{max_size>=size?'image-size-tip':'image-size-error'}} " hidden="{{!tempFilePath||is_update_pic}}">
  限制上传大小2M,当前图片大小为{{size_unit_m}}M,{{max_size>=size?'大小合适':'图片过大,请重新选择!'}}
view>

<view class="oper-list" hidden="{{!tempFilePath}}">
  <view class="oper-item" bindtap="backPage">
    返回
  view>
  <view class="oper-item" bindtap="uploadPic" hidden="{{is_update_pic}}">
    上传
  view>
view>

小程序 样式

.choose-pic {
  height: 88rpx;
  align-items: center;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #616EFB;
  color: #fff;
  width: 80%;
  margin: 20rpx 10%;
  border-radius: 16rpx;
}

page {
  font-family: Source Han Sans CN;
  background: #fff;
}

.pre-view-image {
  display: flex;
  width: 100%;
  align-items: center;
  justify-content: center;
  margin-top: 100rpx;
}

.pre-view-image image {
  border-radius: 8rpx;
}

.oper-list {
  display: flex;
  position: fixed;
  align-items: center;
  width: 100%;
  bottom: 0rpx;
  height: 112rpx;
  border-top: 1rpx solid #E8E9EE;
}

.oper-item {
  flex: 1;
  background: #616EFB;
  color: #fff;
  margin: 0rpx 50rpx;
  height: 78rpx;
  border-radius: 12rpx;
  font-size: 30rpx;
  align-items: center;
  display: flex;
  justify-content: center;
}

.image-size {
  height: 88rpx;
  display: flex;
  align-items: center;
  font-size: 28rpx;
  background: #EBF3FF;
  margin: 32rpx;
  color: #424656;
  padding-left: 24rpx;
}

.image-size-title {
  padding-right: 24rpx;
}

.image-size-value {
  font-weight: 700;
}

.image-size-error {
  font-size: 26rpx;
  margin: 32rpx;
  color: #F3273C;
  padding-left: 24rpx;
}

.image-size-tip {
  font-size: 26rpx;
  margin: 32rpx;
  color: #7A7D88;
  padding-left: 24rpx;
}

.upload-pic-btn {
  width: 100%;
  text-align: center;
  margin-top: 40%;

}

.upload-pic-btn image {
  width: 360rpx;
  height: 248rpx;

}

小程序JS

const app = getApp();
const http = require('../../../utils/http.js');
const api = require('../../../config.js');
const utils = require('../../../utils/util.js');
const dateHelper = require('../../../utils/date.js');
const operHelper = require('../../../utils/oper.js');
const messageHelper = require('../../../utils/message.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tempFilePath: '',
    tempFiles: '',
    max_size: 1024 * 1024 * 2,//最大2M
    size: 5,
    size_unit_m: 0,//格式化大小 M
    goods_info: null,
    upload_btn_pic: '',
    base_url: '',
    is_update_pic: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    console.log(getCurrentPages());
    let _this = this;
    let index = Number(options.index);

    _this.setData({
      upload_btn_pic: app.globalData.wxgh_oauth_url + '/Image/upload-pic.svg',
      index: index
    });

    let pages = getCurrentPages();
    let prePages = pages.filter(f => { return f.route === 'pages/BillBusiness/GoodsFiles/GoodsFiles' });
    let prepagesLen = prePages.length;
    if (prepagesLen > 0) {
      let tempGoods = prePages[prepagesLen - 1].data.goods_list[index];
      _this.setData({
        goods_info: tempGoods,
        offlie_url: prePages[prepagesLen - 1].data.upload_pic_down_url,
      });

      if (tempGoods.pic) {
        let shopid = app.globalData.shopid;
        _this.setData({
          is_update_pic: true
        });
        if (shopid.startsWith('9') || shopid.startsWith('8')) {
          _this.setData({
            tempFilePath: app.globalData.wxgh_oauth_url + tempGoods.pic + '&random2=' + Date.now()
          });
        } else {
          //多台机,指定上传到指定的服务器
          _this.setData({
            tempFilePath: "https://XXX" + tempGoods.pic + '&random2=' + Date.now()
          });
        }
      }
    }
  },

  openModalPic: function () {
    let _this = this;
    _this.setData({
      tempFilePath: '',
      tempFiles: '',
      size: 0,
      size_unit_m: 0
    });
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],//只选择压缩的
      sourceType: ['album', 'camera'],
      success: res => {
        console.log('success')
        console.log(res)
        if (res.errMsg === 'chooseImage:ok') {
          let _tempFilePaths = res.tempFilePaths;
          let _tempFiles = res.tempFiles;
          let _size = _tempFiles[0].size;
          _this.setData({
            tempFilePath: _tempFilePaths[0],
            size_unit_m: (_size / 1024 / 1024).toFixed(2),
            size: _size,
            is_update_pic: false
          });
        }
      },
      fail: f => {
        console.log(f)
      },
      complete: c => {
        console.log('complete')
        console.log(c)
      }
    })
  },

  backPage: function () {
    wx.navigateBack({
      delta: 0,
    })
  },

  preView: function () {
    let _this = this;
    let _tempFilePath = _this.data.tempFilePath;
    wx.previewImage({
      urls: [_tempFilePath],
      success: r => {
        console.log(r)
      },
      fail: f => {
        console.log(f)

      },

    })
  },

  uploadPic: function () {
    let _this = this;
    let _tempFilePath = _this.data.tempFilePath;
    if (!_tempFilePath) {
      wx.showToast({
        title: '请先选择图片!',
        icon: 'none'
      })
      return;
    }

    if (_this.data.size > _this.data.max_size) {
      wx.showToast({
        title: '图片内容过大,请重新选择!',
        icon: 'none'
      })
      return;
    }

    let goods = _this.data.goods_info;
    let shopid = app.globalData.shopid + '';
    let uploadPath = '';
    if (shopid.startsWith('9')) {
      uploadPath = app.globalData.wxgh_oauth_url + '/' + api.uploadPic;
    } else if (shopid.startsWith('1')) {
      uploadPath = "https://xxx" + '/' + api.uploadPic;
    }
    else {
      uploadPath = app.globalData.wxgh_oauth_url + '/' + api.uploadPic;
    }

    wx.showLoading({
      title: '上传中...',
      mask: true
    })

    wx.uploadFile({
      filePath: _tempFilePath,
      name: 'file',
      url: uploadPath,

      formData: {
        "item_name": goods.item_name,
        "shopid": app.globalData.shopid,
        "sort_value": '0',
        "item_no": goods.item_no,
        "openid": app.globalData.openid,
        "offlie_url": _this.data.offlie_url
      },
      header: {
        "Content-Type": "multipart/form-data",
        "chartset": "utf-8"
      },
      timeout: 60000,
      success: res => {
        console.log(res)
        console.log(JSON.parse(res.data))
        let _res = JSON.parse(res.data);

        if (_res.success) {

          let extensionNameIndex = _tempFilePath.lastIndexOf('.');
          let _extensionName = _tempFilePath.substr(extensionNameIndex)

          let pages = getCurrentPages();
          let prePages = pages.filter(f => { return f.route === 'pages/BillBusiness/GoodsFiles/GoodsFiles' });
          let prepagesLen = prePages.length;
          if (prepagesLen > 0) {
            let tempGoodsList = prePages[prepagesLen - 1].data.goods_list;

            tempGoodsList[_this.data.index].pic = _res.data.path + '?=' + Date.now();
            let picList = prePages[prepagesLen - 1].data.pic_list;
            if (picList.filter(f => { return f.item_no === goods.item_no }).length === 0) {
              picList.push({
                item_no: goods.item_no,
                pic_name: goods.item_no + _extensionName + '?=' + Date.now(),
                pic_path: '/itempic/' + shopid + '/' + goods.item_no + '/'
              });
              prePages[prepagesLen - 1].setData({
                pic_list: picList
              });

            }
            prePages[prepagesLen - 1].setData({
              goods_list: tempGoodsList
            });

          }

          wx.showModal({
            content: '上传图片成功!',
            showCancel: false,
            confirmText: '确定',

            success: r => {
              wx.navigateBack()
            }
          })

        } else {
          wx.showModal({
            content: _res.message,
            showCancel: false,
            confirmText: '关闭'
          })
        }

      },
      fail: f => {
        console.log('上传失败~');
        console.log(f)
        wx.showModal({
          content: f.errMsg,
          showCancel: false,
          confirmText: '关闭'
        })
      },
      complete: c => {
        console.log('上传完成~');
        console.log(c)
        wx.hideLoading({

        })

      }
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

.net core 实现接口

处理图片

 #region 上传图片
        [HttpPost]
        [DontWrapResult]
        public async Task UploadPic(IFormFile file)
        {
            var _result = new Result();
            try
            {
                var shopid = _httpContext.HttpContext.Request.Form["shopid"].ToString();
                var item_no = _httpContext.HttpContext.Request.Form["item_no"].ToString();
                var item_name = _httpContext.HttpContext.Request.Form["item_name"].ToString();
                var sort_value = _httpContext.HttpContext.Request.Form["sort_value"].ToString();
                var openid = _httpContext.HttpContext.Request.Form["openid"].ToString();
                var offlie_url = _httpContext.HttpContext.Request.Form["offlie_url"].ToString();
                string oper_id = "";
                var operinfo = await _operInfoRepository.FirstOrDefaultAsync(i => i.shopid == shopid && i.openid == openid);
                if (operinfo == null)
                {
                    _result.success = false;
                    _result.message = "操作员不存在,请重新绑定操作员!";
                    return _result;

                }

                oper_id = operinfo.oper_id;
                offlie_url = offlie_url.Trim();

                int sortValue = 0;
                if (!string.IsNullOrWhiteSpace(sort_value))
                {
                    int.TryParse(sort_value.Trim(), out sortValue);
                }
                var fileName = file.FileName;
                string Extension = Path.GetExtension(fileName);//获取文件的源后缀
                if (string.IsNullOrEmpty(Extension))
                {
                    _result.message = "文件上传的原始名称错误,没有找到文件后缀";
                    _result.success = false;
                    return _result;
                }
                fileName = item_no + Extension;
                string rootdir = AppContext.BaseDirectory;
                DirectoryInfo Dir = Directory.GetParent(rootdir);
                string root = Dir.FullName;
                var dissss = Environment.CurrentDirectory;

                string dicPath = Path.Combine(root + "/wwwroot/itempic/" + shopid + "/" + item_no);
                if (!Directory.Exists(dicPath))
                {
                    Directory.CreateDirectory(dicPath);
                }

                var fullName = dicPath + "/" + fileName;
                if (File.Exists(fullName))
                {
                    File.Delete(fullName);
                }
                //打开上传文件的输入流
                Stream stream = file.OpenReadStream();
                //开始保存拷贝文件
                file.CopyTo(new FileStream(fullName, FileMode.Create));
                stream.Dispose();
//将上传到服务器上的图片,转存到指定IP的客户机器
var saveResult = await _sheetDataService.SendOfflineUploadPic(new BossHelpUploadPicRequest() { itemno = item_no, shopid = shopid, upitempicurl = offlie_url, file_name = fileName, oper_id = oper_id }); Logger.Error("SendOfflineUploadPic:" + JsonConvert.SerializeObject(saveResult)); if (saveResult.Code == 0) { _result.message = saveResult.Message; _result.success = false; _result.data = saveResult.Data; return _result; } if (_itemInfoPicRepository.Count(a => a.shopid == shopid && a.item_no == item_no) == 0) { var itemInfoPic = new ItemInfoPic() { sort_value = sortValue, shopid = shopid, add_date = DateTime.Now, item_name = item_name, item_no = item_no, openid = openid, pic_name = fileName, pic_path = "/itempic/" + shopid + "/" + item_no + "/", }; await _itemInfoPicRepository.InsertAsync(itemInfoPic); } _result.data = new { temp_data = saveResult.Data, path = "/itempic/" + shopid + "/" + item_no + "/" + fileName }; _result.success = true; } catch (Exception ex) { _result.success = false; _result.message = ex.Message; Logger.Error("UploadPic 异常:" + ex.Message + "|" + ex.StackTrace); } return _result; } #endregion

实现将保存服务器上图片,转存到指定的客户机器

 #region 上传图片到产品端

        [DontWrapResult]
        public async Task<Response> SendOfflineUploadPic(BossHelpUploadPicRequest model)
        {
            var _result = new Response();

            try
            {
                //string sfile = @"E:	estpic	estbosshelp.jpg";
                //sfile = model.filePath;
                string upload_url = model.upitempicurl + "/api/ItemApi/UploadFile";// "http://xxx/api/ItemInfo/UploadFile";
                string rootdir = AppContext.BaseDirectory;
                System.IO.DirectoryInfo Dir = System.IO.Directory.GetParent(rootdir);
                //string root = Dir.Parent.Parent.Parent.FullName;
                string root = Dir.FullName;
                string localPath = System.IO.Path.Combine(root + "/wwwroot/itempic/" + model.shopid + "/" + model.itemno + "/" + model.file_name);
                string fileName = localPath;// sfile;//文件全路径(e:abc.txt)
                string safeFileName = System.IO.Path.GetFileName(fileName);//文件名(abc.txt)

                System.Net.WebClient client = new System.Net.WebClient();
                client.Credentials = System.Net.CredentialCache.DefaultCredentials;
                client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data
                client.QueryString["fname"] = safeFileName;
                client.QueryString["item_no"] = model.itemno;
                client.QueryString["oper_id"] = model.oper_id;
                byte[] fileb = client.UploadFile(new Uri(upload_url), "POST", fileName);
                string res = System.Text.Encoding.UTF8.GetString(fileb);

                var _data = JsonConvert.DeserializeObject(res.Replace("
", ""));
                if (_data == null)
                {
                    _result.Message = "返回null";
                    _result.Code = 0;
                    return _result;
                }
                else
                {
                    if (_data.success == "false")
                    {
                        _result.Message = _data.message;
                        _result.Code = 0;
                        return _result;
                    }

                    _result.Data = _data;
                    _result.Code = 1;
                } }
            catch (Exception ex)
            {
                Logger.Error("SendOfflineUploadPic异常:" + model.shopid + ",Message:" + ex.Message + ",StackTrace:" + ex.StackTrace);
                _result.Message = "SendOfflineUploadPic异常:" + model.shopid + ",Message:" + ex.Message + ",StackTrace:" + ex.StackTrace;
                _result.Message = ex.Message;
                _result.Data = new BossHelpUploadPicResponse() { message = ex.StackTrace.ToString() };
                _result.Code = 0;
                return _result;
            }

            return _result;

        }

 效果

原文地址:https://www.cnblogs.com/WQ1992/p/14877732.html