微信小程序实现多图片的上传

1.在微信小程序上,实现多图片的上传在wxml文件中实现页面布局。

<view style="width:100%;float:left;margin-top:25rpx;margin-left:40rpx;padding-bottom:120rpx;" class="weui-uploader__bd">

         <view class="weui-uploader__files">
              <block wx:for="{{pics}}" wx:for-item="image" wx:key="item">
               <view class="weui-uploader__file">
                 <image src="../../../images/warehouse/scanCode_delete.png" wx:if="{{image!=''}}"
                 bindtap="img_delete" class="image_view_css" data-index="{{index}}" 
                 data-sign="{{disabl}}"></image>
                 <image class="weui-uploader__img" wx:if="{{image!=''}}" src="image" bindtap="previewImage"></image> 
                 <!--这里是显示图片在页面上用for循环遍历--> 
               </view>
              </block>
            </view>
            
            <view class="weui-uploader__input-box {{isShow?'true':'hideTrue'}}">
              <view class="weui-uploader__input" bindtap="chooseImage" data-sign="{{disabl}}"></view>
            </view>
            
</view>

2.这里页面样式的布局实现。


.weui-uploader__bd {
  margin-bottom: -4px;
  margin-right: -9px;
  overflow: hidden;
}
.weui-uploader__file {
  float: left;
  margin-right: 15px;
  margin-bottom: 9px;
}
.image_view_css{
  width:60rpx;
  height: 60rpx;
  position: absolute;
  z-index: 5;
  margin-left: 65px;
  margin-top: -25rpx
}
.weui-uploader__img {
  display: block;
  width: 79px;
  height: 79px;
}
.weui-uploader__input-box {
  float: left;
  position: relative;
  margin-right: 9px;
  margin-bottom: 9px;
  width: 77px;
  height: 77px;
  border: 1px solid #d9d9d9;
}
.weui-uploader__input-box:before, .weui-uploader__input-box:after {
  content: " ";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #d9d9d9;
}
.weui-uploader__input-box:before {
  width: 2px;
  height: 39.5px;
}
.weui-uploader__input-box:after {
  width: 39.5px;
  height: 2px;
}
.weui-uploader__input {
  position: absolute;
  z-index: 1;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}
.hideTrue {
  display: none
}

3.在js层的实现中在在data变量中先定义好
pics: [],
count: [1, 2, 3],
isShow:true,
变量
1)onload的方法中首先要加载

isShow: (options.isShow == "true" ? true : false)

2)页面布局形成的为:

3)在实现图片的选择上传中点击空白的页面增加图片调用执行方法

 wx.chooseImage({
      count: 3 - pics.length, // 最多可以选择的图片张数,默认9
      sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
      success: function (res) {
        var tempFilesSize = res.tempFiles[0].size;  //获取图片的大小,单位B 这可以做图片上传的大小控制限制
       //if(tempFilesSize <= 2000000)//图片小于或者等于2M时 可以执行获取图片
        console.log("上传的图片大小:", tempFilesSize);
        var imgSrc = res.tempFilePaths;
        console.log(imgSrc)
        //for(var i=0;i<pics.length;i++){
        //  if(pics[i]==''){
        //    pics.splice(i, 1);
        //  }
        // }
        pics = pics.concat(imgSrc); //将调用的接口返回的值存放在数组中
        console.log("上传的时候:pics:",pics)
        // 控制触发添加图片的最多时隐藏
        if (pics.length >= 3) { //这里是判断上传的图片超多3张后就隐藏上传的图标按钮。
          console.log("111")
          _this.setData({
            isShow: (!_this.data.isShow)
          })
        } else {
          console.log("222")
          _this.setData({
            // isShow: (_this.data.isShow)
          })
        }
        _this.setData({
          pics: pics
        })
      },

在 图片的上传后success成功返回值中在开发工具上是以http://开头返回图片文路径,手机上返回的是wxfile:// 开头的
在这里插入图片描述
在这里插入图片描述
这里实现上传错误的图片后删除
在这里插入图片描述

   //删除图片按钮
  img_delete: function (e) {
    var that = this;
    console.log("这里点击了删除图片")
    var arr = that.data.pics;
    for(var i=0;i<arr.length;i++){
      if (i == e.currentTarget.dataset.index){
        arr.splice(i,1);
      }
    }
    that.setData({
      isShow: true,
      pics: arr,
    })
    }
  },

而实现图片的预览调用的方法是:

  previewImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.pics
    })
  },

实现将图片上传到后台的服务器上,在js中调用的方法

//对保存了图片数组pics做一个for循环。
 wx.uploadFile({
              url: url + "/WxController/upload",
              filePath: pics[0], //这里微信的调用方法只能每次上传一张图片所以可以再调用方法前做对数组pics的一个迭代循环。
              name: 'file',
              formData: {
                coNo: app.globalData.staff.coNo,
                lastFolder: 'ProdPaperWx'
              },
              dataType: 'json',
              success: function (res) {
                if (res.statusCode == 200) {
					console.log("成功返回值:",res)
				}
			  }
	})		

在这里插入图片描述后台接口方法/WxController/upload 用java执行

package com.get.controller.util;



import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import com.get.util.BaseController;
@Controller
@RequestMapping(value="/WxController")
public class WxController {
	
	@RequestMapping("/upload")
    @ResponseBody
    public Map<String,Object> upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        Map<String,Object> map=new HashMap<String, Object>();
        String msg="",ret="success",path="",type=null;
        request.setCharacterEncoding("UTF-8");
        String coNo=request.getParameter("coNo");
        String lastFolder =request.getParameter("lastFolder");
        if(!file.isEmpty()){
            String fileName = file.getOriginalFilename();
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if(type!=null){
                if("PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                 String realPath=BaseController.getCustFilePath()+"image/"+coNo+ "/" + lastFolder + "/";
            //这图片存放的路径采用了在指定的方式,在BaseController的getCustFilePath()方法中指定好了  
                 File myFilePath = new File(realPath);
              if (!myFilePath.exists()){//文件夹不存在,生成一个文件夹
               myFilePath.mkdirs();
              }
                    // 自定义的文件名称
                    String trueFileName=coNo+String.valueOf(System.currentTimeMillis())+"."+type;
                    // 设置存放图片文件的路径
                    path=realPath+trueFileName;
                    file.transferTo(new File(path));ret="success";msg="";
                }else {
                 msg="不是我们想要的文件类型,请按要求重新上传!";ret="error";path="";
                }
            }else{
                msg="文件类型为空!";ret="error";path="";
            }
        }else {
            msg="没有找到相对应的文件!";ret="error";path="";
        }
        map.put("ret",ret);
        map.put("msg",msg);
        map.put("path",path);
        return map;
    }
}

这里是BaseController类内的一个指定图片存放路径的方法。

public class BaseController {
	//客户文件存放路径
		public static String getCustFilePath(){
			return "D:/lqb/imge/";
			}
}
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值