微信小程序 递归上传多图

wx.uploadFile 接口每次只支持一张图片上传,而且是个异步方法,所以用递归来解决(来源于网上)

Posted by 昆山吴彦祖 on 2019.03.19

上代码

微信端:

chooseImage() {
const that = this
wx.chooseImage({
count: 9,
success(res) {
//console.log(res)
that.setData({
imageList: res.tempFilePaths
})
}
})
},

    if (需要上传图片的时候){
//递归处理图片上传

let successUp = 0; //成功
let failUp = 0; //失败
let count = 0; //第几张
let url = app.globalData.baseUrl + '/api/order/updateImage/'
that.uploadOneByOne(url,order_id, that.data.imageList, successUp, failUp, count, that.data.imageList.length)
}

//递归上传图片方法 uploadOneByOne:function(url,order_id,imgPaths, successUp, failUp, count, length) { var that = this; wx.showLoading({ title: '正在上传第' + count + '张图片', }) wx.uploadFile({ url: url,//图片上传地址 filePath: imgPaths[count], name: 'image',//示例,使用顺序给文件命名 formData: { customer_id: wx.getStorageSync('customer').id, session: wx.getStorageSync('customer').session, order_id: order_id, }, success: function (e) { successUp++;//成功+1 }, fail: function (e) { failUp++;//失败+1 }, complete: function (e) { console.log(e) count++;//下一张 if (count == length) { //上传完毕,作一下提示 console.log('上传成功' + successUp + ',' + '失败' + failUp); wx.showToast({ title: '上传成功' + successUp, icon: 'success', duration: 2000 }) } else { //递归调用,上传下一张 that.uploadOneByOne(url, order_id, imgPaths, successUp, failUp, count, length); console.log('正在上传第' + count + '张'); } } }) }



服务器端:

// 上传订单图片接口
    public function updateImage(Request $request){
    	$order = Order::find($request->order_id);
    	if(!$order || $order->customer_id!=$request->customer_id){
    		return response()->json([
		        'info' => false, 
		        'message' =>'参数错误'
			]);
    	}
			
    
    	$file = $request->image;
        $path = Storage::disk('admin')->putFile('admin',$file);
		
		// 如果标书字段已经有数据,插入。 否则新增
		if(!empty($order->image)){
			$array = $order->image;
			array_push($array,$path);
			$order->image = $array;
		}else{
			$order->image = array($path);
		}
        

        if($order->save()){
			return response()->json([
				'info' => true,
			]);
		}
    	else{
    		return response()->json([
				'info' => false,
			]);
		}
    }