本文使用的技术栈:小程序开发、SpringBoot、MyBatis、Redis
这里前端用到了Vant Weapp的UI库 https://github.com/youzan/vant-weapp
<view class="page"> <form bindsubmit='send'> <van-cell-group> <van-field required clearable left-icon="gift" name="goodsName" label="商品名称" icon="question" placeholder="请输入商品名" bind:click-icon="onClickIcon" /> <van-field type="textarea" label="描述" left-icon="records" name="goodsDesc" placeholder="请输入5-50个字" autosize required border="{{ false }}" /> </van-cell-group> <view class="image_content"> <view class='image' wx:for="{{img_url}}"> <image class="deleteImg" mode="aspectFill" data-index='{{index}}' src="/img/deleteImg.png" bindtap="deleteImg"></image> <image class="moment_img" mode="aspectFill" data-index='{{index}}' src="{{item}}" bindtap="previewImg"></image> </view> <view class='image' style='display:{{hideAdd?"none":"block"}}'> <image bindtap="chooseimage" class="moment_img" src='/img/addImg.png'></image> </view> </view> <van-cell-group> <van-field required clearable left-icon="gold-coin" name="goodsPrice" label="单价" icon="question" placeholder="请输入数字" bind:click-icon="onClickIcon" /> <van-field value="1" label="数量" left-icon="exchange" name="goodsNum" placeholder="" required /> <van-field left-icon="chat" name="goodsPhone" label="联系方式" required /> <van-field left-icon="location" value="" name="goodsAddress" label="交易地点" placeholder="例:学瀚楼下" required /> </van-cell-group> <button class="publishBtn" type="primary" form-type='submit'>发布</button> </form> </view>
chooseimage: function () { var me = this; //动态更新当前用户可以上传的图片数 var count = 9 - that.data.img_url.length; wx.chooseImage({ count: count, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { if (res.tempFilePaths.length > 0) { //把每次选择的图push进数组 let img_url = that.data.img_url; for (let i = 0; i < res.tempFilePaths.length; i++) { img_url.push(res.tempFilePaths[i]) } me.setData({ img_url: img_url }) //图如果满了9张,不显示添加图片图标 if (that.data.img_url.length >= 8) { me.setData({ hideAdd: 1 }) } else { me.setData({ hideAdd: 0 }) } } } }) }
//预览图片 previewImg:function(e){ var me = this; var img_url = me.data.img_url; var index = e.target.dataset.index; wx.previewImage({ urls: img_url, current : img_url[index], success:function(res){ console.log(res); } }) }, //删除图片 deleteImg: function (e){ var me = this; var img_url = me.data.img_url; var index = e.target.dataset.index; img_url.splice(index, 1); me.setData({ img_url: img_url, //若当前图片超过9张,则隐藏添加图标;少于9张则显示添加图标。 hideAdd: me.data.img_url.length <9 ? false : true }) },
//上传商品信息 send:function(e){ var me = this; console.log(e); var goodsName = e.detail.value.goodsName; var goodsDesc = e.detail.value.goodsDesc; var goodsPrice = e.detail.value.goodsPrice; var goodsNum = e.detail.value.goodsNum; var goodsAddress = e.detail.value.goodsAddress; var goodsPhone = e.detail.value.goodsPhone; var thirdSession = wx.getStorageSync("thirdsession") wx.showLoading({ title: '发布中--', }) var serverUrl = app.serverUrl; wx.request({ url: serverUrl + '/goods/uploadGoods', data: { thirdSession: thirdSession, goodsName: goodsName, goodsDesc: goodsDesc, goodsPrice: goodsPrice, goodsNum: goodsNum, goodsAddress: goodsAddress, goodsPhone: goodsPhone, }, method: "GET", success: function (res) { wx.hideLoading(); console.log(res.data.data); //商品信息上传成功后,上传商品图片 me.uploadGoodsImg(res.data.data); } }) }
//上传图片 uploadGoodsImg: function (goodsId){ var me = this; var imgFilePaths = me.data.img_url; var count = me.data.count; var serverUrl = app.serverUrl; wx.showLoading({ title: '上传图片中--', }) wx.uploadFile({ url: serverUrl + '/goods/uploadGoodsImg', filePath: imgFilePaths[count], name: 'file', formData: { goodsId: goodsId }, success: function (res) { //可统计成功上传图片数 }, fail: function (res) { //可统计上传失败图片数 }, complete: function (res) { count++; me.setData({ count: count }) if (count >= imgFilePaths.length) { var data = JSON.parse(res.data); console.log(data); wx.hideLoading(); if (data.status == 200) { wx.hideLoading(); wx.showToast({ title: '上传成功!~~', icon: 'success' }); me.setData({ count: 0 }) } else if (data.status == 500) { wx.showToast({ title: data.msg, }); } } else { //图片未上传完,递归调用本方法。 me.uploadGoodsImg(goodsId); } } }) }
//保存商品信息 @GetMapping("/uploadGoods") public IMoocJSONResult uploadFace(String thirdSession,String goodsName, String goodsDesc,double goodsPrice,String goodsPhone, int goodsNum,String goodsAddress) throws Exception { if (StringUtils.isBlank(thirdSession)) { return IMoocJSONResult.errorMsg("thirdSession is none"); } String value = (String) redis.get("Wxuser-redis-session:"+thirdSession); System.out.println(value); if (StringUtils.isBlank(value)) { return IMoocJSONResult.errorMsg("session timeout"); } //解析json格式的str JSONObject json = JSONObject.parseObject(value); String openId = json.getString("openid"); String goodsId = sid.nextShort(); Goods goods = new Goods(); goods.setId(goodsId); goods.setSellerId(openId); goods.setSellerPhone(goodsPhone); goods.setAddress(goodsAddress); goods.setGoodsDesc(goodsDesc); goods.setLikeCounts(0); goods.setGoodsName(goodsName); goods.setPrice(goodsPrice); goods.setGoodsNum(goodsNum); goodsService.saveGoods(goods); return IMoocJSONResult.ok(goodsId); }
@PostMapping(value="/uploadGoodsImg" ,headers="content-type=multipart/form-data") public IMoocJSONResult uploadGoodsImg(String goodsId,@RequestParam("file") MultipartFile[] files) throws Exception { //文件保存的命名空间 String fileSpace="D:/cunjin-xianyu-test"; //保存到数据库的相对路径 String uploadPathDB="/"+goodsId+"/img"; FileOutputStream fileOutputStream=null; InputStream inputStream= null; try { if(files != null && files.length>0) { String fileName= files[0].getOriginalFilename(); if (StringUtils.isNotBlank(fileName)) { //文件保存的最终路径 String finalPath = fileSpace + uploadPathDB + "/" + fileName; //设置数据库保存的路径 uploadPathDB+=("/"+fileName); File outFile=new File(finalPath); if (outFile.getParentFile()!=null || !outFile.getParentFile().isDirectory()) { //创建父文件夹 outFile.getParentFile().mkdirs(); } fileOutputStream = new FileOutputStream(outFile); inputStream = files[0].getInputStream(); IOUtils.copy(inputStream, fileOutputStream); }else { return IMoocJSONResult.errorMsg("上传出错"); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return IMoocJSONResult.errorMsg("上传出错"); }finally { if(fileOutputStream!=null) { fileOutputStream.flush(); fileOutputStream.close(); } } GoodsImg goodsImg = new GoodsImg(); goodsImg.setGoodsId(goodsId); goodsImg.setImg(uploadPathDB); goodsService.saveGoodsImg(goodsImg); return IMoocJSONResult.ok("上传成功"); }