微信小程序多张图片上传

一、小程序段

 1.index.wxml页面

复制代码
 <view>

 <view class="three">图片</view>
  <view class="weui-uploader">
    <view class='pics' wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
        <image class='weui-uploader__img' src="{{item}}" data-index="{{index}}" mode="aspectFill" bindtap="previewImg">
                  <icon type='cancel' class="delete-btn" data-index="{{index}}" catchtap="deleteImg"></icon>
        </image>
    </view>

    <view class="tp_cont {{tj_ycang?'':'hide'}}" bindtap="chooseImg">
      <view class="tp_add">+</view>
    </view>

     </view>
</view>
复制代码

2.index.wxss

复制代码
.three{
   margin-top: 27rpx;
 }
 .weui-uploader{
   margin-top: 16rpx;
 }
 .tp_add{
   width: 152rpx;
   height: 152rpx;
   border-radius: 10rpx;
   opacity: 1;
   border: 2rpx dashed #999999;
   display: flex;
   justify-content: center;
   align-items: center;
   font-size: 59rpx;
 }
 
 .pics {
   float:left;
   position:relative;
   margin-right:15px;
   margin-bottom:15px;
   }
   .pics image{
     width: 152rpx;
     height: 152rpx;
   }
   .delete-btn{
     width: 20rpx;
     height: 20rpx;
     position: absolute;
     top: -15rpx;
     right: -5rpx;
   }
   .weui-uploader{
     padding: 10rpx;
   }
 
复制代码

3.index.js

复制代码
// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
   imgs: [] 

   
  },
 
  chooseImg: function (e) {
   var that = this;
   var imgs = this.data.imgs;
   if (imgs.length >= 9) {
    this.setData({
     lenMore: 1
    });
    setTimeout(function () {
     that.setData({
      lenMore: 0
     });
    }, 2500);
    return false;
   }
   wx.chooseImage({
    // count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
     // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
     var tempFilePaths = res.tempFilePaths;
  var successUp=0;
  var failUp=0;
  var count=0;
that.uploadOneByOne(tempFilePaths,successUp,failUp,count,tempFilePaths.length);

     var imgs = that.data.imgs;
     // console.log(tempFilePaths + '----');
     for (var i = 0; i < tempFilePaths.length; i++) {
      if (imgs.length >= 9) {
       that.setData({
        imgs: imgs
       });
       return false;
      } else {
       imgs.push(tempFilePaths[i]);


      }
     }
  
     that.setData({
      imgs: imgs
     });
  
        
      

    }
   });
  },

  uploadOneByOne(  imgPaths, successUp, failUp, count, length) {
   var that = this;
   wx.uploadFile({
      url:"https://*******/AjApi/saveImg",  //上传地址地址
      header:{
 
         'content-type':'multipart/form-data',
         Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5a2Z5Y2g5aWOIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvbmFtZWlkZW50aWZpZXIiOiJzZDc4czhlMzc3ZnlkaGRmeXd0cjZ3eXJmMG93cDJoamhxd3l2YnBsZHhnb2V1bmxkdXdzbGJqZyIsImV4cCI6MTY2MTc1ODQwMiwiaXNzIjoiY2JhIiwiYXVkIjoiY2JhIn0.F8WoLwheY_iAXCzu16vn3bE1XaRQdug5KB7T1D3RH2k"
        },
        formData: {
           
              openID: "oMW0M5aKMJrHO-Q1cV9ataMC5Ih8",
                
                  AjID: 9,
                  fj_type: 'qsz',
        },
   filePath: imgPaths[count],
   name: "files", //后台接收的文件名  必须和服务器端对应上
   success: function(e) {
   successUp++; //成功+1
   },
   fail: function(e) {
   failUp++; //失败+1
   },
   complete: function(e) {
   count++; //下一张
   if (count == length) {
   TODO: 上传完毕后跳转页面
   wx.showToast({
   title: '发布成功',
   icon: 'success',
   duration: 2000
   })
   }
   else {
   //递归调用,上传下一张
   that.uploadOneByOne( imgPaths, successUp, failUp, count, length);
   }
   }
   })
   },


  // 删除图片
  deleteImg: function (e) {
   var imgs = this.data.imgs;
   var index = e.currentTarget.dataset.index;
   imgs.splice(index, 1);
   this.setData({
    imgs: imgs
   });
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
   var index = e.currentTarget.dataset.index;
    //所有图片
   var imgs = this.data.imgs;
   wx.previewImage({
    //当前显示图片
    current: imgs[index],
    //所有图片
    urls: imgs
   })
  }
 
})
复制代码

4. 服务器段代码  ,这里采用  asp.net core

复制代码
 [HttpPost]
        public async Task<IActionResult> SaveImg(List<IFormFile> files, int AjID, string fj_type, string appid)

        {  

            if (files == null || files.Equals(string.Empty))
            {
                return Json(new { count = 0, msg = "请选择文件后再上传!! files参数为空!!" });
            }
            string path = "";
             
            long size = files.Sum(f => f.Length);
         
            string contentRootPath = _webHostEnvironment.ContentRootPath;
            path = contentRootPath + "/UpFile/" + AjID + "/" + fj_type + "/";
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {

                    Console.WriteLine($"上传文件{formFile.FileName}中");


                    string fileExt = Path.GetExtension(formFile.FileName); //文件扩展名,不含“.”
                    if (!ImgExt.Contains(fileExt))
                    {
                        return Json(new { msg = "only   " + ImgExt.ToString() + " img  file allowed upload " + fileExt, count = 0 });

                    }

                    long fileSize = formFile.Length; //获得文件大小,以字节为单位
                    if (fileSize / 1024 / 1024 > 20)
                    {
                        return Json(new
                        {
                            msg = " video filesize must be less than 20MB ",
                            count = 0
                        });
                    }
                    //string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名
                    // string newFileName = AjID + fileExt; //随机生成新的文件名
                  
                    DirectoryInfo di = new DirectoryInfo(path);

                    if (!di.Exists) { di.Create(); }

                  string   filePath = path + Guid.NewGuid().ToString()+fileExt;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {

                        await formFile.CopyToAsync(stream);

                  

                    }
                }
                else {
                    return Json(new { count = 0,  msg="请选择文件后再上传!!"   });

                }
            }

            return Json(new { count = files.Count, size=size,fileList=this.GetFile(path, "/" + AjID + "/" + fj_type + "/")   });
        }
复制代码

 

posted on   码农at突泉  阅读(278)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示