实习小白,仅供参考
该篇前提,后端封装好了图片存储接口,不然要自己写接口
1.微信小程序图片上传,页面效果
wxml代码(这里list.order.upload_img是原程序网页输出图片地址,而uploadImgUrl自己写的):
<view class="fui-cell uploadImg">
<view class="fui-cell-label" style="width:200rpx;">图片上传:</view>
<view style="margin-top: 20rpx; display: flex;justify-content: flex-start;align-items: center;">
<!--list.order.upload_img是我这小程序wxml显示后台输出的图片地址,根据你们程序自己找 -->
<image src="{{list.order.upload_img?list.order.upload_img:uploadImgUrl}}" style="width: 150rpx;height: 150rpx;"></image>
<view wx:if="{{uploadImgUrl.length>0||list.order.upload_img.length>0}}" class="imgDelCss" bindtap="imgDelBtn">+</view><
<view wx:if="{{!(uploadImgUrl.length>0||list.order.upload_img.length>0)}}" bindtap="chooseImage" class="addUploadImgCss">+</view>
<view>
</view>
</view>
</view>
</view>
css代码:
.uploadImg{
position: relative;
}
.addUploadImgCss{
position: absolute;
display: flex;
justify-content: center;
align-items: center;
width: 148rpx;
height:148rpx;
border:1px solid rgb(211, 211, 211);
font-size: 30px;color: rgb(211, 211, 211);
}
js代码:
data: {
uploadImgUrl:'',
},
chooseImage:function(t){
var that = this;
wx.chooseImage({
count: 1, //最多可以选择的图片总数
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
//启动上传等待中...
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 3000
})
wx.uploadFile({
url: 'http://www.weiqing2.cn/app/ewei_shopv2_api.php?i=1&r=util.uploader.upload',//后台原本封装了保存图片的接口,保存完返回一个绝对路径一个相对路径
filePath: tempFilePaths[0],
name: 'file',
header: {
"Content-Type": "multipart/form-data"
},
success: function (res) {
var data = JSON.parse(res.data);
if(data.files.length>0){
that.setData({
uploadImgUrl:data.files[0].url,
})
// 获取到图片保存地址进行写表操作
that.getEvidenceImg(data.files[0].url)
}
},
fail: function (res) {
wx.hideToast();
wx.showModal({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function (res) { }
})
}
});
}
});
},
getEvidenceImg(img){
//获取当前展示页面数据表相关id
let id = this.data.list.order.id;
wx.request({
url: 'http://www.weiqing2.cn/app/ewei_shopv2_api.php?i=1&r=order.pay.updateOrderVoucher',//在pay后台页面写了个更新数据表方法updateOrderVoucher修改保存图片地址
data:{
id:id,
img:img
},
success(res){
console.log('图片地址已经写入数据库');
},
fail(err){
// console(err)
}
})
},
后端php代码(将获取图片地址写入数据表,后端我的是用微擎):
public function updateOrderVoucher()
{
global $_W, $_GPC;
$id = intval($_GPC['id']);//获取id
$img = trim($_GPC['img']);//获取图片地址
$order = pdo_fetch("Select id from ".tablename("相关数据表XXX")." Where id={$id}");
if ($order) {//存在该id数据
$imgRes = pdo_update('相关数据表XXX',array('upload_img'=>$img),array('id'=>$id));//改写数据
if ($imgRes) {
return app_json(1);
}
}
return app_error("订单更新失败");
}
原来程序封装的存储图片文件php自己写,这里就不放出来了,主要是获取到图片移动成功返回图片地址就ok了,和php上传图片差不多。
图片删除就放下一篇分享