上一节为大家介绍了页面间的传值
这一节继续我们的开发流程,这节课我们来实现“新增动态”页面的实现
实现效果:


首先我们在app.json中新增页面路径
"pages": [
"pages/login/login",
"pages/home/home",
"pages/userCenter/userCenter",
"pages/home/dynamicDeatil/dynamicDeatil",
"pages/home/addNewDynamic/addNewDynamic"
],
编译之后生成目录及4个文件

开始编写
addNewDynamic.json
{
"usingComponents": {},
"navigationBarTitleText": "新增动态"
}
addNewDynamic.wxml
<view class="container">
<view class="inputContainer">
<textarea class="inputView" placeholder="请输入发布内容" auto-height="false" bindinput="textInputListen" bindblur="bindTextAreaBlur"></textarea>
<view class="line"></view>
</view>
<view class="photoContainer">
<view class="photoItem" catchtap="selectPhoto">
<image wx:if="{{selectedPhoto}}" src="{{selectedPhoto}}" class="selectedPhoto" mode="aspectFill"> </image>
<image class="selectPhotoIcon" wx:else src="/images/home/selectPhoto.png"></image>
<image class="canclePhoto" hidden="{{!selectedPhoto}}" src="/images/home/guanbi.png" catchtap="cancleSelectPhoto"> </image>
</view>
</view>
<view class="postTap" catchtap="postNewDynamic" style="position:absolute ,backgroundColor: red ,width:{{width - 200}}rpx,height:100rpx,top:{{height - 100}}rpx,left : {{20}}rpx">发布
</view>
</view>
addNewDynamic.wxss
.container {
width: 100%;
display: flex;
flex-direction: column;
padding: 20rpx 0rpx 0rpx 0rpx ;
}
.inputContainer {
width: 100%;
margin-top: 20rpx;
}
.inputView {
width: 690rpx;
margin-left: 30rpx;
margin-top: 20rpx;
padding: 10rpx 10rpx 10rpx 10rpx;
font-size: 28rpx;
color: #333;
}
.line {
width: 690rpx;
height: 1rpx;
margin-left: 30rpx;
background-color: lightgray;
margin-top: 20rpx;
}
.photoContainer {
width: 100%;
margin-top: 60rpx;
}
.photoItem {
width: 150rpx;
height: 150rpx;
border: 1rpx solid lightgray;
margin-left: 30rpx;
}
.selectedPhoto{
width: 150rpx;
height: 150rpx;
}
.selectPhotoIcon{
width: 80rpx;
height: 80rpx;
position: relative;
top: 35rpx;
left: 35rpx;
}
.canclePhoto{
width: 40rpx;
height: 40rpx;
position: relative;
left: 130rpx;
top: -180rpx;
background-color: white;
border-radius: 20rpx;
}
.postTap{
position:fixed;
bottom:60rpx;
background-color:#50c4e7;
width: 700rpx;
height: 90rpx;
border-radius: 6rpx;
font-size: 30rpx;
color: white;
line-height: 90rpx;
text-align: center;
}
addNewDynamic.js
// pages/home/addNewDynamic/addNewDynamic.js
var qiniuUploader = require("../../../utils/qiniuUploader.js");
var requestTool = require("../../../utils/request.js");
const onfire = require("../../../utils/onfire.js");
Page({
/**
* 页面的初始数据
*/
data: {
selectedPhoto: "",//选择的图片文件
imageURL:"",//发布的图片链接
contentText: "",//发布的文字内容
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
},
//选择照片
selectPhoto: function() {
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
var tempFilePaths = res.tempFilePaths
console.log(tempFilePaths);
var url = tempFilePaths[0];
that.setData({ //将选择的照片绑定数据
selectedPhoto: url
});
},
})
},
//取消选择
cancleSelectPhoto: function() {
this.setData({
selectedPhoto: ""
});
},
bindTextAreaBlur: function(e) {
console.log(e.detail.value);
this.setData({
contentText: e.detail.value //绑定发文内容
})
},
bindFormSubmit: function(e) {
console.log(e.detail.value.textarea);
this.setData({
contentText: e.detail.value
});
this.submitAllData();
},
postNewDynamic:function(){
this.startReadytAllData();
},
startReadytAllData: function () {
if(!this.data.contentText){
wx.showModal({
title: '温馨提示',
content: '请输入文字内容',
showCancel: false,
});
return;
}
if (!this.data.selectedPhoto) {
wx.showModal({
title: '温馨提示',
content: '请选择一张照片',
showCancel: false,
});
return;
}
//获取图片链接
this. getQiNiuData();
},
getQiNiuData:function(){
var that = this;
var pathUrl = "/qiniu/token/upload-img";
var paraData = {
type : 1,
};
requestTool.getRequest(pathUrl, paraData, that.getQiNiuSuccess, that.getQiNiuFailed);
},
getQiNiuSuccess:function(data){
console.log("请求七牛成功" + data);
this.didUploadChooseImage(data);
},
getQiNiuFailed:function(){
console.log("请求失败");
},
/**
* 获取图片链接
*/
didUploadChooseImage: function (paraDic) {
var token = paraDic.token;
var key = paraDic.filekey;
var domain = paraDic.domain;
var that = this;
var filePath = that.data.selectedPhoto;
qiniuUploader.upload(filePath, (res) => {
that.setData({
'imageURL': res.imageURL,
});
console.log('file url is: ' + res.fileUrl);
that.submitAllData();
}, (error) => {
console.log('error: ' + error);
}, {
region: 'ECN',
domain: domain,
//key: 'customFileName.jpg', // [非必须]自定义文件 key。如果不设置,默认为使用微信小程序 API 的临时文件名
// 以下方法三选一即可,优先级为:uptoken > uptokenURL > uptokenFunc
uptoken: token, // 由其他程序生成七牛 uptoken
//uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken,返回的格式必须是 json 且包含 uptoken 字段,例如: {"uptoken": "[yourTokenString]"}
//uptokenFunc: function () { return '[yourTokenString]'; }
}, (res) => {
console.log('上传进度', res.progress)
console.log('已经上传的数据长度', res.totalBytesSent)
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
}, () => {
// 取消上传
}, () => {
// `before` 上传前执行的操作
}, (err) => {
// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
});
},
submitAllData:function(){
var that = this;
var pathUrl = "/dynamic/commit";
var postData = {
url : that.data.imageURL,
text : that.data.contentText,
};
requestTool.postRequest(pathUrl, postData, that.submitDynamixSuccess, that.submitDynamicFailed);
},
submitDynamixSuccess:function(data){
console.log("发布成功");
onfire.fire("reloadDynamicFunction");
wx.navigateBack();
},
submitDynamicFailed:function(){
console.log("发布失败");
},
})
引用的第三方js文件“qiniuUploader.js”
// created by gpake
(function() {
var config = {
qiniuRegion: '',
qiniuImageURLPrefix: '',
qiniuUploadToken: '',
qiniuUploadTokenURL: '',
qiniuUploadTokenFunction: null,
qiniuShouldUseQiniuFileName: false
}
module.exports = {
init: init,
upload: upload,
}
// 在整个程序生命周期中,只需要 init 一次即可
// 如果需要变更参数,再调用 init 即可
function init(options) {
config = {
qiniuRegion: '',
qiniuImageURLPrefix: '',
qiniuUploadToken: '',
qiniuUploadTokenURL: '',
qiniuUploadTokenFunction: null,
qiniuShouldUseQiniuFileName: false
};
updateConfigWithOptions(options);
}
function updateConfigWithOptions(options) {
if (options.region) {
config.qiniuRegion = options.region;
} else {
console.error('qiniu uploader need your bucket region');
}
if (options.uptoken) {
config.qiniuUploadToken = options.uptoken;
} else if (options.uptokenURL) {
config.qiniuUploadTokenURL = options.uptokenURL;
} else if(options.uptokenFunc) {
config.qiniuUploadTokenFunction = options.uptokenFunc;
}
if (options.domain) {
config.qiniuImageURLPrefix = options.domain;
}
config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
}
function upload(filePath, success, fail, options, progress, cancelTask, before, complete) {
if (null == filePath) {
console.error('qiniu uploader need filePath to upload');
return;
}
if (options) {
updateConfigWithOptions(options);
}
if (config.qiniuUploadToken) {
doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
} else if (config.qiniuUploadTokenURL) {
getQiniuToken(function() {
doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
});
} else if (config.qiniuUploadTokenFunction) {
config.qiniuUploadToken = config.qiniuUploadTokenFunction();
if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
console.error('qiniu UploadTokenFunction result is null, please check the return value');
return
}
doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
} else {
console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
return;
}
}
function doUpload(filePath, success, fail, options, progress, cancelTask, before, complete) {
if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
console.error('qiniu UploadToken is null, please check the init config or networking');
return
}
var url = uploadURLFromRegionCode(config.qiniuRegion);
var fileName = filePath.split('//')[1];
if (options && options.key) {
fileName = options.key;
}
var formData = {
'token': config.qiniuUploadToken
};
if (!config.qiniuShouldUseQiniuFileName) {
formData['key'] = fileName
}
before && before();
var uploadTask = wx.uploadFile({
url: url,
filePath: filePath,
name: 'file',
formData: formData,
success: function (res) {
var dataString = res.data
// // this if case is a compatibility with wechat server returned a charcode, but was fixed
// if(res.data.hasOwnProperty('type') && res.data.type === 'Buffer'){
// dataString = String.fromCharCode.apply(null, res.data.data)
// }
try {
var dataObject = JSON.parse(dataString);
//do something
var fileUrl = config.qiniuImageURLPrefix + '/' + dataObject.key;
dataObject.fileUrl = fileUrl
dataObject.imageURL = fileUrl;
console.log(dataObject);
if (success) {
success(dataObject);
}
} catch(e) {
console.log('parse JSON failed, origin String is: ' + dataString)
if (fail) {
fail(e);
}
}
},
fail: function (error) {
console.error(error);
if (fail) {
fail(error);
}
},
complete: function(err) {
complete && complete(err);
}
})
uploadTask.onProgressUpdate((res) => {
progress && progress(res)
})
cancelTask && cancelTask(() => {
uploadTask.abort()
})
}
function getQiniuToken(callback) {
wx.request({
url: config.qiniuUploadTokenURL,
success: function (res) {
var token = res.data.uptoken;
if (token && token.length > 0) {
config.qiniuUploadToken = token;
if (callback) {
callback();
}
} else {
console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
}
},
fail: function (error) {
console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
}
})
}
function uploadURLFromRegionCode(code) {
var uploadURL = null;
switch(code) {
case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
}
return uploadURL;
}
})();
完结:
submitDynamixSuccess:function(data){
console.log("发布成功");
onfire.fire("reloadDynamicFunction");
wx.navigateBack();//返回上个页面
},
发表成功之后,onfire.on("reloadDynamicFunction'');
发送订阅消息,让home.js触发刷新数据的事件。
内容浅显易懂,有问题随时提问~
下一节:
传送门:
十四:动态详情页面的实现与分析
网友评论