微信小程序 1.主表附表同时提交表单 2.动态新增删除view 3.上传文件(附Java源码)

wxml代码:

<view class="page">
  <view class='head'></view>

  <view class='content'>
    <form bindsubmit='formSubmit'>
      <view class="page-section">
        <view class="weui-cell_input">
          <input class="weui-input" name="goodsName" placeholder="商品名称" />
        </view>
      </view>

      <view class="page-section">
        <view class="weui-cell_input">
          <input class="weui-input" name="browseVolume" placeholder="浏览量" />
        </view>
      </view>

      <view class="page-section">
        <view class="weui-cell_input">
          <input class="weui-input" name="reloadVolume" placeholder="转载量" />
        </view>
      </view>

      <view class="page-section">
        <view class="weui-cell_input">
          <input class="weui-input" name="style" placeholder="风格类型" />
        </view>
      </view>

      <view class="page-section">
        <view class="weui-cell_input">
          <input class="weui-input" name="color" placeholder="色系类型(选填)" />
        </view>
      </view>

      <view class="page-section">
        <view class='weui-cells__title'>是否显示</view>
        <switch checked name="isShow"/>
      </view>

      <view wx:for="{{info.details}}" wx:for-item="detail" wx:key="key">
        <view class="page-section-upload" bindtap="chooseImage" id="imgUrl-{{index}}" hover-class='bc_red'>
          <view class='weui-cells__title'>上传图片</view>
          <image class='upload' src="{{detail.imgUrl}}"></image>
        </view>

        <view class="page-section">
          <view class="weui-cell_input">
            <input class="weui-input"id="imgName-{{index}}"bindinput="setImgName"placeholder="图片说明(选填)"/>
          </view>
        </view>

        <view class="page-section">
          <view class="weui-cell_input">
            <input class="weui-input"id="space-{{index}}"placeholder="空间类型"bindinput="setSpace"/>
          </view>
        </view>
      </view>

      <view class='weui-detail'>
        <view class='weui-detail-button' bindtap='addDetail' hover-class='bc_red'>添加详情</view>
        <view class='weui-detail-button' bindtap='removeDetail' hover-class='bc_red'>删除详情</view>
      </view>

      <button formType="submit" type="primary" style='width:700rpx;'>提交</button>
    </form>
  </view>

  <view class='foot'></view>
</view>

js代码:

function Detail(imgUrl, imgName, space) {
  this.imgUrl = imgUrl;
  this.imgName = imgName;
  this.space = space;
}

function Info() {
  this.details = [];
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {},
  },

  init: function() {
    let that = this;
    this.setData({
      info: new Info(),
    });
  },

  chooseImage(e) {
    const that = this
    wx.chooseImage({
      sourceType: ['album', 'camera'],
      sizeType: ['original'],
      //sizeType: ['original', 'compressed'],
      count: 1,
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '上传中',
        })
        wx.uploadFile({
          url: getApp().api.upload, //此处换上你的接口地址
          filePath: tempFilePaths[0],
          name: 'files',
          header: {
            'Content-Type': 'multipart/form-data'
          },
          formData: {
            'typeName': 'deteilImg' //其他额外的formdata,可不写
          },
          success: function(res) {
            let data = JSON.parse(res.data)
            if (data.code === '0') {
              that.setImgUrl(e, data.data);
            }
            wx.hideLoading()
          },
          fail: function(res) {
            console.log('fail');
          },
        })
      }
    })
  },

  addDetail() {
    let info = this.data.info;
    info.details.push(new Detail());
    this.setData({
      info: info
    });
  },

  removeDetail() {
    let info = this.data.info;
    info.details.pop();
    this.setData({
      info: info
    });
  },

  setImgUrl: function(e, imgUrl) {
    let index = parseInt(e.currentTarget.id.replace("imgUrl-", ""));
    let info = this.data.info;
    info.details[index].imgUrl = imgUrl;
    this.setData({
      info: info
    });
  },

  setImgName: function(e) {
    let index = parseInt(e.currentTarget.id.replace("imgName-", ""));
    let imgName = e.detail.value;
    let info = this.data.info;
    info.details[index].imgName = imgName;
    this.setData({
      info: info
    });
  },

  setSpace: function(e) {
    let index = parseInt(e.currentTarget.id.replace("space-", ""));
    let space = e.detail.value;
    let info = this.data.info;
    info.details[index].space = space;
    this.setData({
      info: info
    });
  },

  //表单提交
  formSubmit(e) {
    console.info(e.detail.value)
    let goods = e.detail.value
    wx.showLoading({
      title: '上传中',
    })
    wx.request({
      url: getApp().api.addGoods,
      data: {
        goodsName: goods.goodsName,
        browseVolume: goods.browseVolume === "" ? 0 : goods.browseVolume,
        reloadVolume: goods.reloadVolume === "" ? 0 : goods.reloadVolume,
        style: goods.style,
        color: goods.color,
        isShow:goods.isShow?0:1,
        goodsDetails: this.data.info.details
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json'
      },
      success:function(res){
        wx.hideLoading()
        if(res.data.code === "0"){
          wx.showToast({
            title: '添加成功',
            icon:'success',
            duration:1500
          })
        }
        if (res.data.code === "-1") {
          wx.showToast({
            title: '添加失败',
            duration: 1500
          })
        }
      },
      fail:function(res){

      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.init();
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})

 wxss代码:

.page {

}

.page-section{
  display: flex;
  flex-direction: row;
  align-items: center;
  border-bottom: 2rpx solid #eee;
  height: 80rpx;
}

.page-section-upload{
  display: flex;
  flex-direction: row;
  align-items: center;
  border-bottom: 2rpx solid #eee;
  height: 77px;
}

.weui-cells__title{
  width: 140rpx;
  font-size: 30rpx;
  margin-left: 30rpx;
  border: 0rpx solid #eee;
}

.weui-cell_input{
  border: 0rpx solid #eee;
  margin-left: 30rpx;
}

.weui-input{
  width: 690rpx;
  height: 60rpx;
  min-height: 60rpx;
  font-size: 30rpx;
}

switch{
  margin-left: 470rpx;
}

.upload{
  width: 77px;
  height: 75px;
  margin-left: 30rpx;
}

.weui-detail{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  height: 80rpx;
  margin-bottom: 50rpx;
  border-bottom: 2rpx solid #eee;
}

.weui-detail-button{
  height: 60rpx;
  width: 140rpx;
  line-height: 60rpx;
  font-size: 30rpx;
  text-align: center;
}

 Java上传接口代码:

package com.whjjx.dorabox.controller;

import com.whjjx.dorabox.util.FileUtil;
import com.whjjx.dorabox.util.Json;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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 javax.annotation.Resource;
import java.io.File;

@Controller
@RequestMapping("/file")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileUtil fileUtil;

    @RequestMapping("/upload")
    @ResponseBody
    public Json upload(@RequestParam("files") MultipartFile[] files,@RequestParam("typeName") String typeName){
        Json j = new Json();
        if(files.length < 1){
            j.setCode("-1001");
            j.setMsg("请选择要上传的文件");
            return j;
        }

        StringBuffer sb = new StringBuffer();

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                //调用文件上传
                try {
                    String fileName = file.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    File tempFile = new File("tempFile" + "." + suffix);
                    FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
                    //上传文件名   文件夹/文件
                    String key =  typeName + "/" + System.currentTimeMillis() + "." + suffix;
                    StringBuffer url = new StringBuffer(fileUtil.uploadQiNinCloud(tempFile, key));
                    sb.append(url + ",");
                } catch (Exception e) {
                    log.error("上传文件失败");
                    e.printStackTrace();
                    j.setCode("-1002");
                    j.setMsg("上传文件失败");
                    return j;
                }
            }
        }
        j.setData(sb.substring(0, sb.length() - 1));
        j.setCode("0");
        return j;
    }
}

fileUtil工具类代码 :

package com.whjjx.dorabox.util;

import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.File;

@Component
public class FileUtil {

    @Resource
    private HttpApiService httpApiService;

    @Resource
    private Constant constant;
    
    /**
    *
    * @param file 上传文件
    * @param key 文件夹/文件名
    * @return
    * @throws Exception
    */
   public String uploadQiNinCloud(File file, String key) throws Exception {
       //开始上传
       Configuration cfg = new Configuration(Zone.autoZone());
       UploadManager uploadManager = new UploadManager(cfg);

       Auth auth = Auth.create(Constant.QINIU_ACCESS_KEY, Constant.QINIU_SECRET_KEY);
       String upToken;

       //生成token
       upToken = auth.uploadToken(Constant.QINIU_BUCKET, key);
       try {
           //调用七牛上传
           uploadManager.put(file.getCanonicalPath(), key, upToken);
       } catch (Exception e) {
           e.printStackTrace();
           return null;
       }finally {
           //删除本地文件
           if(file.exists()){
               file.delete();
           }
       }
       return Constant.QINIU_DOMAIN + key;
   }

   
}

Java主附表表单提交接口代码:

package com.whjjx.dorabox.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import java.util.*;

import com.whjjx.dorabox.domain.GoodsDomain;
import com.whjjx.dorabox.domain.bo.AddGoodsBO;
import com.whjjx.dorabox.domain.bo.GoodsBO;
import com.whjjx.dorabox.service.IGoodsService;
import com.whjjx.dorabox.util.Json;

/**
* 描述:商品控制层
* @author zhouzilin
* @date 2019-01-06
*/
@Controller
@RequestMapping("/goods")
public class GoodsController {

	private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private IGoodsService goodsService;

    /**
    * 描述:创建商品
    * @param goods  商品
    */
    @RequestMapping(value = "/save")
	@ResponseBody
    public Json create(@RequestBody AddGoodsBO vo) throws Exception {
       	Json j = new Json();
		try {
			goodsService.addGoods(vo);
			j.setCode("0");
			j.setMsg("成功");
			return j;
		} catch (Exception e) {
			logger.error("Goods出异常了", e);
    		j.setCode("-1");
   	 		j.setMsg("出异常了");
			return j;
		}
    }

}

 AddGoodsBO类:

package com.whjjx.dorabox.domain.bo;

import java.util.List;

import com.whjjx.dorabox.domain.GoodsDetailsDomain;
import com.whjjx.dorabox.domain.GoodsDomain;

public class AddGoodsBO extends GoodsDomain{
	
	private List<GoodsDetailsDomain> goodsDetails;

	public List<GoodsDetailsDomain> getGoodsDetails() {
		return goodsDetails;
	}

	public void setGoodsDetails(List<GoodsDetailsDomain> goodsDetails) {
		this.goodsDetails = goodsDetails;
	}
	
}

service层代码:

@Override
@Transactional(rollbackFor = Exception.class)
public void addGoods(AddGoodsBO bo) {
    // TODO Auto-generated method stub
	Integer num = goodsMapper.insertSelective(bo);
	if(num > 0) {
		for (GoodsDetailsDomain domain : bo.getGoodsDetails()) {
			domain.setGoodsId(bo.getId());
			domain.setImgName(null == domain.getImgName() ? " " : domain.getImgName());
		}
		gds.addList(bo.getGoodsDetails());
	}
		
}

 

微信小程序 1.主表附表同时提交表单 2.动态新增删除view 3.上传文件(附Java源码)