龙空技术网

使用Net Core实现微信小程序上传图片

W1780 89

前言:

目前朋友们对“正在载入微信net”都比较关心,看官们都需要分析一些“正在载入微信net”的相关资讯。那么小编在网上搜集了一些关于“正在载入微信net””的相关内容,希望我们能喜欢,朋友们快快来学习一下吧!

后台环境:.net core3.1

服务器是: 华为云 Linux云服务器

小程序代码

WXML文件:

<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}}">  限制上传大小1M,当前图片大小为{{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>

JS代码文件:

wx.uploadFile API 使用

data: {    tempFilePath: '',    tempFiles: '',    max_size: 1024 * 1024 * 1,//最大2M    size: 0,    size_unit_m: 0,//格式化大小 M    goods_info: null,    upload_btn_pic: '',    base_url: '',    is_update_pic: false,    is_upload_temp_pic: false  },  /**   * 生命周期函数--监听页面加载   */  onLoad: function (options) {    console.log(options);    console.log(getCurrentPages());    let _this = this;    let index = Number(options.index);    let isUploadTempPic = index === -1;    _this.setData({      upload_btn_pic: operHelper.getImageDomain() + '/Image/upload-pic.svg',      index: index,      is_upload_temp_pic: isUploadTempPic    });    let pages = getCurrentPages();    let route = 'pages/BillBusiness/GoodsFiles/GoodsFiles';    if (isUploadTempPic) {      route = 'pages/BillBusiness/GoodsFile/GoodsFile';    }    let prePages = pages.filter(f => { return f.route === route });    let prepagesLen = prePages.length;    if (prepagesLen > 0) {      let tempGoods = null;      let prePage = prePages[prepagesLen - 1];      if (isUploadTempPic) {        tempGoods = {          pic: prePage.data.pic,          item_no: prePage.data.goodCode,          item_name: prePage.data.goodName,        };      } else {        tempGoods = prePage.data.goods_list[index];      }      _this.setData({        goods_info: tempGoods,        offlie_url: prePage.data.upload_pic_down_url,      });      if (tempGoods.pic) {        _this.setData({          is_update_pic: true,          tempFilePath: 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)      }    })  },  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 = operHelper.getImageDomain() + '/' + 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,        "is_temp": _this.data.is_upload_temp_pic ? '1' : '0',        "support_image_to_product": operHelper.supportItemImageToProduct() ? "1" : "0"      },      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 isTemp = _this.data.is_upload_temp_pic;          let route = 'pages/BillBusiness/GoodsFiles/GoodsFiles';          if (isTemp) {            route = 'pages/BillBusiness/GoodsFile/GoodsFile';          }          let prePages = pages.filter(f => { return f.route === route });          let prepagesLen = prePages.length;          if (prepagesLen > 0) {            let pic = (utils.isTestEnv() ? operHelper.getImageDomain() : operHelper.getCdnImageDomain()) + '/' + _res.data.path + '?random=' + Date.now();            if (isTemp) {              prePages[prepagesLen - 1].setData({                pic: pic              });            } else {              let tempGoodsList = prePages[prepagesLen - 1].data.goods_list;              tempGoodsList[_this.data.index].pic = pic;              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({        })      }    })  },

后台代码:部分关键代码

IFormFile

        [HttpPost]        [DontWrapResult]        public async Task<Result> UploadPic(IFormFile file)        {                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/" + 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();        }

小程序页面的效果:

上传页面

上传后页面

标签: #正在载入微信net #netpost图片 #net可以做微信小程序吗