160 lines
2.8 KiB
JavaScript
160 lines
2.8 KiB
JavaScript
// pages/community/add.js
|
|
const config = require("../../config/config")
|
|
const { api } = require("../../utils/api")
|
|
Page({
|
|
|
|
/**
|
|
* 页面的初始数据
|
|
*/
|
|
data: {
|
|
content: '',
|
|
ossIds: [],
|
|
fileList: []
|
|
},
|
|
|
|
/**
|
|
* 生命周期函数--监听页面加载
|
|
*/
|
|
onLoad(options) {
|
|
|
|
},
|
|
|
|
upload(e) {
|
|
const {
|
|
files
|
|
} = e.detail;
|
|
console.log(files);
|
|
this.setData({
|
|
fileList: files
|
|
})
|
|
},
|
|
remove(e) {
|
|
const {
|
|
index
|
|
} = e.detail;
|
|
const {
|
|
fileList
|
|
} = this.data
|
|
fileList.splice(index, 1);
|
|
this.setData({
|
|
fileList
|
|
});
|
|
},
|
|
input(e) {
|
|
const value = e.detail.value
|
|
this.setData({
|
|
content: value
|
|
})
|
|
},
|
|
submit() {
|
|
if (this.data.content.length === 0) {
|
|
wx.showModal({
|
|
content: '请输入这一刻的想法',
|
|
})
|
|
return
|
|
}
|
|
wx.showLoading({
|
|
title: '请稍后',
|
|
})
|
|
// 上传图片
|
|
const uploadTasks = this.data.fileList.map(file => this.uploadSingle(file));
|
|
Promise.all(uploadTasks)
|
|
.then(ossIds => {
|
|
console.log("全部上传成功", ossIds);
|
|
// ossIds 是一个 [id1, id2, id3...]
|
|
this.save(ossIds);
|
|
})
|
|
.catch(err => {
|
|
console.error("有上传失败", err);
|
|
wx.showToast({
|
|
title: '上传失败',
|
|
icon: 'none'
|
|
});
|
|
});
|
|
|
|
},
|
|
|
|
save(ids){
|
|
const data = {content:this.data.content,ossIds: ids,title:this.data.content}
|
|
api('/post/add','POST',data,'json').then(res => {
|
|
if (res.code === 200){
|
|
wx.navigateBack()
|
|
} else{
|
|
wx.showModal({
|
|
content: res.msg
|
|
})
|
|
}
|
|
})
|
|
},
|
|
|
|
uploadSingle(file) {
|
|
console.log(file);
|
|
return new Promise((resolve, reject) => {
|
|
wx.uploadFile({
|
|
filePath: file.url,
|
|
name: 'file',
|
|
header: {
|
|
'Authorization': 'Bearer ' + wx.getStorageSync('token'),
|
|
},
|
|
url: config.baseUrl + '/oss/upload',
|
|
success: res => {
|
|
const data = JSON.parse(res.data);
|
|
if (data.code === 200) {
|
|
resolve(data.data.file.id); // 返回 ossId
|
|
} else {
|
|
reject(data);
|
|
}
|
|
},
|
|
fail: reject
|
|
});
|
|
})
|
|
},
|
|
/**
|
|
* 生命周期函数--监听页面初次渲染完成
|
|
*/
|
|
onReady() {
|
|
|
|
},
|
|
|
|
/**
|
|
* 生命周期函数--监听页面显示
|
|
*/
|
|
onShow() {
|
|
|
|
},
|
|
|
|
/**
|
|
* 生命周期函数--监听页面隐藏
|
|
*/
|
|
onHide() {
|
|
|
|
},
|
|
|
|
/**
|
|
* 生命周期函数--监听页面卸载
|
|
*/
|
|
onUnload() {
|
|
|
|
},
|
|
|
|
/**
|
|
* 页面相关事件处理函数--监听用户下拉动作
|
|
*/
|
|
onPullDownRefresh() {
|
|
|
|
},
|
|
|
|
/**
|
|
* 页面上拉触底事件的处理函数
|
|
*/
|
|
onReachBottom() {
|
|
|
|
},
|
|
|
|
/**
|
|
* 用户点击右上角分享
|
|
*/
|
|
onShareAppMessage() {
|
|
|
|
}
|
|
}) |