微信小程序多图上传及后台处理(后台用thinkphp3.2)

 

 index.wxml页面

 1 <view class="info">
 2     <form bindsubmit="save">
 3     <view class="info-list">
 4         <view class="list-left">店铺logo<text></text></view>
 5         <view class="list-right">
 6             <image src="{{store_logo?store_logo:'/images/add.png'}}" style="width: 128rpx;height: 128rpx;" bindtap="uploadLogo"></image>
 7         </view>
 8     </view>
 9     <view class="info-list">
10         <view class="list-left">店铺名称<text>*</text></view>
11         <view class="list-right">
12             <input placeholder="请输入店铺名称" name="store_name" value="{{store_info.store_name}}"></input>
13         </view>
14     </view>
15     <view class="info-list">
16         <view class="list-left">店铺地址<text>*</text></view>
17         <view class="list-right">
18             <picker bindchange="bindPadChange" value="{{index}}" range="{{position_list}}" class="picker" style="margin-left: 10rpx;">
19                 <view class="picker" class="input-item">
20                     {{position_list[index]}}
21                 </view>
22             </picker>
23         </view>
24     </view>
25         <view class="info-list">
26         <view class="list-left">店铺铺号<text>*</text></view>
27         <view class="list-right">
28             <input placeholder="请输入店铺铺号" name="store_num" value="{{store_info.store_num}}"></input>
29         </view>
30     </view>
31     <view class="info-list">
32         <view class="list-left">联系人<text>*</text></view>
33         <view class="list-right">
34             <input placeholder="请输入联系人" name="link_name" value="{{store_info.link_name}}"></input>
35         </view>
36     </view>
37     <view class="info-list">
38         <view class="list-left">联系方式<text>*</text></view>
39         <view class="list-right">
40             <input placeholder="请输入联系方式" name="link_tel" value="{{store_info.link_tel}}"></input>
41         </view>
42     </view>
43     <view class="info-list list1">
44         <view class="list-left">主营品牌及产品<text>*</text></view>
45     </view>
46     <view class="field">
47         <textarea name="major_brand" value="{{store_info.major_brand}}" placeholder="请认真填写主营的品牌及产品,内容会在店铺头部显示" placeholder-class="font-size:24rpx"></textarea>
48     </view>
49 
50     <view class="list1" style="border-top: 1px solid #ddd;">
51         <view class="list-left">店铺照片:<text>(可以上传三张店铺图片) </text></view>
52         <button class="Btn" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="" bindtap='uploader' name="images">上传图片</button>
53         <view class="goods-print">
54             <view class="print-view" wx:for="{{imagesList}}">
55                 <image src="{{item}}"></image>
56                 <view class="detail" bindtap="delImg" data-index="{{index}}">×</view>
57             </view>
58         </view>
59     </view>
60 
61     <view class="releaseBtn">
62         <view class="redColor">带*号店铺属性为必填项</view>
63         <button formType="submit">提交</button>
64     </view>
65     </form>
66 </view>

index.wxss页面

page{
  background-color: #fff;
}
.info-list{
  width: 100%;
  display: flex;
flex-direction: row;
padding:28rpx;
border-bottom: 1px solid #ddd;
color: #000000;

}
.list-right{
  width: 500rpx;
}
.list-left text{
  color: red;
}
.list-right .radio{
  padding-right: 30rpx;
}
.list1{
  border-bottom: none;
  color: #000;
  padding:28rpx;
}
.list-right text{
  color: #999;
}
.goods-print {
display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  clear: both;
  margin-top: 20rpx;
}
.goods-print .print-view{
  width:230rpx ;
  height: 230rpx;
  position: relative;
}
.goods-print .print-view .detail{
  position: absolute;
  width: 30rpx;
  height: 30rpx;
  text-align: center;
  line-height: 30rpx;
  background-color: red;
  color: #fff;
  border-radius: 50%;
  top:0;
  right: 0;
}
.goods-print image {
  width: 220rpx;
  height: 220rpx;
}
.Btn{
  width: 200rpx;
  background-color: #09bb07;
  margin:20rpx 0 ;
  float: left;
  color: #fff;
}
.releaseBtn{
  margin:20rpx 0 100rpx 0 ;
  text-align: center;
}
.releaseBtn .redColor{
  color: red;
  font-size: 24rpx;
}
.releaseBtn button{
  width: 80%;
  background-color: #ff5d37;
  color: #fff;
  margin-top: 20rpx;
}
.field textarea{
  width: 680rpx;
  margin:0 28rpx 28rpx 28rpx;
  border-radius: 8rpx;
  border: 1px solid #ddd;
  padding:28rpx;
}
.list1{
  border:none;
}
View Code

index.js代码

  1 var server = require('../../utils/server');
  2 var app = getApp();
  3 const API_URL = app.globalData.API_URL;
  4 Page({
  5 
  6   data: {
  7     position_list: [], //位置列表
  8     position_id: [], //位置id列表
  9     index: 0,
 10     store_info: {},
 11     store_logo: '',
 12     up_logo: '',
 13     imagesList: [],
 14   },
 15   onLoad: function (options) {
 16     
 17   },
 18   // 产品类型
 19   bindPadChange: function (e) {
 20     this.setData({
 21       index: e.detail.value,
 22     })
 23   },
 24   delImg: function (e) {
 25     var img_index = e.target.dataset.index;
 26     var imgs = this.data.imagesList;
 27 
 28     server.getJSON("/Home/delStoreImg",{img_url:imgs[img_index]},  function (res) {
 29       console.log('删除图片:',res);
 30     });
 31 
 32     imgs.forEach((item, index) => {
 33       if (index == img_index) {
 34         imgs.splice(index, 1);
 35       }
 36     });
 37     this.setData({
 38       imagesList: imgs,
 39     })
 40     console.log('删除后的图片合集', this.data.imagesList);
 41   },
 42   uploader: function () {
 43     var that = this;
 44     let imagesList = [];
 45     let maxSize = 1024 * 1024;
 46     let maxLength = 3;
 47     let flag = true;
 48     wx.chooseImage({
 49       count: 3, //最多可以选择的图片总数
 50       sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
 51       sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
 52       success: function (res) {
 53         wx.showToast({
 54           title: '正在上传...',
 55           icon: 'loading',
 56           mask: true,
 57           duration: 500
 58         })
 59         for (let i = 0; i < res.tempFiles.length; i++) {
 60           if (res.tempFiles[i].size > maxSize) {
 61             flag = false;
 62             wx.showModal({
 63               content: '图片太大,不允许上传',
 64               showCancel: false,
 65               success: function (res) {
 66                 if (res.confirm) {
 67                   console.log('用户点击确定')
 68                 }
 69               }
 70             });
 71           }
 72         }
 73         if (res.tempFiles.length > maxLength) {
 74           wx.showModal({
 75             content: '最多能上传' + maxLength + '张图片',
 76             showCancel: false,
 77             success: function (res) {
 78               if (res.confirm) {
 79                 console.log('确定');
 80               }
 81             }
 82           })
 83         }
 84         if (flag == true && res.tempFiles.length <= maxLength) {
 85           that.data.imagesList = that.data.imagesList.concat(res.tempFilePaths);
 86           that.setData({
 87             // imagesList: res.tempFilePaths
 88             imagesList: that.data.imagesList
 89           })
 90         }
 91         console.log('上传图片合集', that.data.imagesList);
 92       },
 93       fail: function (res) {
 94         console.log('上传失败结果:', res);
 95       }
 96     })
 97   },
 98   uploadLogo: function () {
 99     var that = this;
100     let maxSize = 1024 * 1024;
101     let flag = true;
102     wx.chooseImage({
103       count: 1, //最多可以选择的图片总数
104       sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
105       sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
106       success: function (res) {
107         wx.showToast({
108           title: '正在上传...',
109           icon: 'loading',
110           mask: true,
111           duration: 500
112         })
113         if (res.tempFiles[0].size > maxSize) {
114           flag = false;
115           wx.showModal({
116             content: '图片太大,不允许上传',
117             showCancel: false,
118             success: function (res) {
119               if (res.confirm) {
120                 console.log('用户点击确定')
121               }
122             }
123           });
124         }
125         if (flag == true) {
126           wx.uploadFile({
127             url: API_URL + '/Home/uploadStoreImg',
128             filePath: res.tempFiles[0].path,
129             name: 'uploadfile_ant',
130             header: {
131               "Content-Type": "multipart/form-data"
132             },
133             formData: {
134               type: 1,
135               id: 0,
136             },
137             success: function (result) {
138               var e = JSON.parse(result.data);
139               that.setData({
140                 store_logo: e.img_url,
141                 up_logo: e.result
142               })
143             },
144             fail: function (data) {
145               console.log(data);
146             }
147           });
148         }
149         console.log('店铺logo', that.data.store_logo);
150       },
151       fail: function (res) {
152         console.log('上传失败结果:', res);
153       }
154     })
155   },
156   // 保存
157   save(event) {
158     let self = this,
159       eventDA = event.detail.value;
160     
161     if (eventDA.store_name.length <= 0) {
162       wx.showToast({
163         title: '请输入店铺名称',
164         icon: 'none',
165         duration: 1000
166       });
167       return false;
168     }
169     if (eventDA.store_num.length <= 0) {
170       wx.showToast({
171         title: '请输入店铺铺号',
172         icon: 'none',
173         duration: 1000
174       });
175       return false;
176     }
177     if (self.data.index == 0) {
178       wx.showToast({
179         title: '请选择店铺地址',
180         icon: 'none',
181         duration: 1000
182       });
183       return false;
184     }
185     if (eventDA.link_name.length <= 0) {
186       wx.showToast({
187         title: '请输入联系人',
188         icon: 'none',
189         duration: 1000
190       });
191       return false;
192     }
193     if (eventDA.link_tel.length <= 0) {
194       wx.showToast({
195         title: '请输入联系方式',
196         icon: 'none',
197         duration: 1000
198       });
199       return false;
200     }
201     if (eventDA.major_brand.length <= 0) {
202       wx.showToast({
203         title: '请填写主营的品牌及产品',
204         icon: 'none',
205         duration: 1000
206       });
207       return false;
208     }
209     var user_id = wx.getStorageSync("user").user_id;
210     if(!self.data.store_info || self.data.store_info.length <= 0){
211       var store_id = 0;
212     }else{
213       var store_id = self.data.store_info.store_id;
214     }
215 
216     server.postJSON('/Home/edit_info/',{
217       store_id:store_id,
218       user_id:user_id,
219       position_id1:self.data.position_id[self.data.index],
220       store_name:eventDA.store_name,
221       store_num:eventDA.store_num,
222       link_name:eventDA.link_name,
223       link_tel:eventDA.link_tel,
224       major_brand:eventDA.major_brand,
225       store_logo:self.data.up_logo,
226     },function(res){
227       if(res.data.status == 1){
228         if(store_id > 0){
229           var id = store_id;
230         }else{
231           var id = res.data.list;
232         }
233         if (self.data.imagesList.length > 0) {
234           console.log('图片合集:', self.data.imagesList);
235           for (let i = 0; i < self.data.imagesList.length; i++) {
236             if (self.data.imagesList[i].indexOf("tmp") > 0) {
237               wx.uploadFile({
238                 url: API_URL + '/Home/uploadStoreImg',
239                 filePath: self.data.imagesList[i],
240                 name: 'uploadfile_ant',
241                 header: {
242                   "Content-Type": "multipart/form-data"
243                 },
244                 formData: {
245                   type: 2,
246                   id: id,
247                 },
248                 success: function (data) {
249                   if ((self.data.imagesList.length - 1) == i) {
250 
251 
252                   }
253                 },
254                 fail: function (data) {
255                   console.log(data);
256                 }
257               });
258             }
259           }
260         }
261 
262         wx.showToast({
263           title: '保存成功',
264           duration: 1000
265         });
266         setTimeout(function () {
267           wx.redirectTo({
268             url: '/pages/member/index/index'
269           });
270         }, 1000);
271       }else{
272         var msg = res.data.msg;
273         wx.showToast({
274           title: '' + msg,
275           icon: 'none',
276           duration: 1000
277         });
278       }
279     });
280   }
281 })

后台处理图片上传代码:

 1 <?php
 2 
 3 namespace WXAPI\Controller;
 4 
 5 use Think\Controller;
 6 
 7 class HomeController extends BaseController
 8 {
 9 
10     /**
11      * 析构流函数
12      */
13     public function __construct()
14     {
15         parent::__construct();
16 
17     }
18     /**
19      * 上传店铺图片
20      */
21     public function uploadStoreImg()
22     {
23         $store_id = I('id', 0);
24         $type = I('type', 1);
25         $path = "Public/upload/store/";
26         $path .= date('Y') . "/" . date('m-d') . "/";
27         if (!is_dir($path)) { //判断目录是否存在 不存在就创建
28             mkdir($path, 0777, true);
29         }
30 
31         $allow = ["image/jpg", "image/jpeg", "image/bmp", "image/png",];
32         if ($_FILES["uploadfile_ant"]["error"] > 0) {
33             exit(json_encode(array('status' => -1, 'msg' => '上传失败,错误码:' . $_FILES["uploadfile_ant"]['error'], 'result' => '')));
34         }
35 
36         if (!in_array($_FILES["uploadfile_ant"]["type"], $allow)) {
37             exit(json_encode(array('status' => -1, 'msg' => '上传的文件类型不被允许', 'result' => '')));
38         }
39 
40         if ($_FILES['uploadfile_ant']['size'] > 5 * 1024 * 1024) {
41             exit(json_encode(array('status' => -1, 'msg' => '上传文件过大', 'result' => '')));
42         }
43         $imageName = date("YmdHis", time()) . rand(1111, 9999) . ".jpg";
44         $filepath = $path . $imageName;
45 
46         if (move_uploaded_file($_FILES['uploadfile_ant']['tmp_name'], $filepath)) {
47             $data['store_id'] = $store_id;
48             $data['img_url']  = "/" . $filepath;
49 
50             if ($type == 1) {
51                 exit(json_encode(array('status' => 1, 'msg' => '上传成功', "result" => "/" . $filepath,'img_url'=>SITE_URL."/" . $filepath)));
52             } else {
53                 $res = M('store_images')->add($data);
54                 exit(json_encode(array('status' => 1, 'msg' => '上传成功', "result" => $res)));
55             }
56             
57         }
58         exit(json_encode(array('status' => 1, 'msg' => '上传成功', "result" => "/" . $filepath,'img_url'=>SITE_URL."/" . $filepath)));
59     }
60     /**
61      * 删除店铺图片
62      */
63     public function delStoreImg()
64     {
65         $img_url = I('img_url', '');
66         $type = I('type', 1);
67         
68         if($img_url){
69             $img_arr = explode(SITE_URL,$img_url);
70             $img_info = M('store_images')->where(array('img_url'=>$img_arr[1]))->find();
71             if($img_info){
72                 unlink($_SERVER['DOCUMENT_ROOT'].$img_arr[1]);
73                 M('store_images')->where(array('img_url'=>$img_arr[1]))->delete();
74             }
75             exit(json_encode(array('status' => 1, 'msg' => '删除成功', "result" => '')));
76         }
77     }
78 }

 

posted @ 2020-09-01 10:33  糖糖Y  阅读(939)  评论(0编辑  收藏  举报