1.图片上传
<view class="sectionImg">
<view class="section__title">二寸红底照片</view>
<image class='section__img' data-id="imgOne" src='{{imgOne ? imgOne : plusImg}}' bindtap='chooseImage'></image>
<input type='text' hidden='true' name="imgOne" value='{{imgOneValue}}'/>
<view hidden='{{imgOneStatus}}' class='imgStatus'>{{imgOneTip}}</view>
</view>
- src中imgOne代表现在的变量,plusImg代表原来的变量,原理是用现在的变量代替原来的变量;
- input中value值中imgOneValue变量代表服务器端接收到的地址;
- js代码
Page({
data: {
plusImg: '/image/plus.png',
imgOne: '',
},
//上传图片
chooseImage: function (e) {
// 初始化七牛配置
initQiniu();
var imgId = e.currentTarget.dataset.id;
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
// 交给七牛上传
qiniuUploader.upload(tempFilePaths[0], (upRes) => {
// console.log(upRes);
// 修改数据
var data = {};
data[imgId] = tempFilePaths;
var imgValue = imgId+'Value';
data[imgValue] = upRes.imageURL;
that.setData(data);
}, (error) => {
}
);
}
})
},
- hidden中的imgOneStatus变量和imgOneTip变量是表单验证时的字段
- 表单验证提交代码
/**
* 设置验证字段
*/
function setValidate(obj) {
obj.WxValidate = app.WxValidate(
{
level: {
required: true
},
name: {
required: true
},
imgOne: {
required: true
},
}, {
level: {
required: '请选择报考等级'
},
name: {
required: '请输入您的姓名'
},
imgOne: {
required: '请上传二寸红底照片'
},
}
);
}
// 提交表单
formSubmit: function (e) {
console.log('form发生了submit事件,携带数据为:', e.detail.value)
var that = this
var meInfo = this.data.userInfo;
var requestValue = e.detail.value;
var formId = e.detail.formId;
// console.log(e);
// 去掉提示
var data = {};
for (var i in requestValue) {
var status = i + 'Status';
data[status] = true;
}
this.setData(data);
//提交错误描述
if (!this.WxValidate.checkForm(e)) {
data = {};
var errs = this.WxValidate.errorList;
for (var i in errs) {
var tip = errs[i].param + 'Tip';
var status = errs[i].param + 'Status';
var msg = errs[i].msg;
data[tip] = msg;
data[status] = false;
}
console.log(data);
this.setData(data);
return false
}
}
2.在js中必须初始化app;var app = getApp();
3.一定要记得引入文件
const config = require("../../config");
const qiniuUploader = require("../../utils/qiniuUploader");