Browse Source

修复图片上传和显示问题:1. 将eggbar/create-post.js图片上传限制从9张改为5张;2. 修复eggbar/eggbar.js中图片URL解析问题,确保images字段正确解析为数组;3. 同步更新其他相关文件

pull/18/head
Default User 1 month ago
parent
commit
d0b65d70bb
  1. 21
      pages/eggbar/create-post.js
  2. 26
      pages/eggbar/eggbar.js
  3. 123
      pages/profile/authentication/index.js
  4. 2
      project.private.config.json
  5. 19
      server-example/server-mysql.js

21
pages/eggbar/create-post.js

@ -53,16 +53,16 @@ Page({
}, },
chooseImage() { chooseImage() {
if (this.data.images.length >= 9) { if (this.data.images.length >= 5) {
wx.showToast({ wx.showToast({
title: '最多只能上传9张图片', title: '最多只能上传5张图片',
icon: 'none' icon: 'none'
}); });
return; return;
} }
wx.chooseImage({ wx.chooseImage({
count: 9 - this.data.images.length, count: 5 - this.data.images.length,
sizeType: ['compressed'], sizeType: ['compressed'],
sourceType: ['album', 'camera'], sourceType: ['album', 'camera'],
success: (res) => { success: (res) => {
@ -185,6 +185,7 @@ Page({
const uploadedImages = []; const uploadedImages = [];
let uploadedCount = 0; let uploadedCount = 0;
let hasError = false;
tempImagePaths.forEach((tempPath, index) => { tempImagePaths.forEach((tempPath, index) => {
wx.uploadFile({ wx.uploadFile({
@ -201,19 +202,31 @@ Page({
const data = JSON.parse(res.data); const data = JSON.parse(res.data);
if (data.success && data.imageUrl) { if (data.success && data.imageUrl) {
uploadedImages.push(data.imageUrl); uploadedImages.push(data.imageUrl);
} else {
console.error('上传图片失败:', data.message || '未知错误');
hasError = true;
} }
} catch (e) { } catch (e) {
console.error('解析上传响应失败:', e); console.error('解析上传响应失败:', e);
hasError = true;
} }
} else {
console.error('上传图片失败,HTTP状态码:', res.statusCode);
hasError = true;
} }
}, },
fail: (err) => { fail: (err) => {
console.error('上传图片失败:', err); console.error('上传图片失败:', err);
hasError = true;
}, },
complete: () => { complete: () => {
uploadedCount++; uploadedCount++;
if (uploadedCount === tempImagePaths.length) { if (uploadedCount === tempImagePaths.length) {
resolve(uploadedImages); if (hasError && uploadedImages.length === 0) {
reject(new Error('所有图片上传失败,请重试'));
} else {
resolve(uploadedImages);
}
} }
} }
}); });

26
pages/eggbar/eggbar.js

@ -90,6 +90,32 @@ Page({
// 正确处理后端返回的响应格式 // 正确处理后端返回的响应格式
let newPosts = res.data && res.data.posts ? res.data.posts : []; let newPosts = res.data && res.data.posts ? res.data.posts : [];
// 处理images字段,确保它是一个数组
newPosts = newPosts.map(post => {
if (post.images) {
// 如果images是字符串,尝试解析为JSON数组
if (typeof post.images === 'string') {
try {
post.images = JSON.parse(post.images);
// 确保解析后是数组
if (!Array.isArray(post.images)) {
post.images = [];
}
} catch (e) {
// 解析失败,设置为空数组
post.images = [];
}
} else if (!Array.isArray(post.images)) {
// 如果不是字符串也不是数组,设置为空数组
post.images = [];
}
} else {
// 如果images不存在,设置为空数组
post.images = [];
}
return post;
});
// 如果是第一页且没有数据,使用默认动态数据 // 如果是第一页且没有数据,使用默认动态数据
if (this.data.page === 1 && (!newPosts || newPosts.length === 0)) { if (this.data.page === 1 && (!newPosts || newPosts.length === 0)) {
newPosts = [ newPosts = [

123
pages/profile/authentication/index.js

@ -1,4 +1,5 @@
// pages/profile/authentication/index.js // pages/profile/authentication/index.js
const API = require('../../../utils/api.js');
Page({ Page({
/** /**
* 页面的初始数据 * 页面的初始数据
@ -6,6 +7,8 @@ Page({
data: { data: {
idCardFront: '', // 身份证人像面 idCardFront: '', // 身份证人像面
idCardBack: '', // 身份证国徽面 idCardBack: '', // 身份证国徽面
idcard1: null, // 身份证正面文件信息
idcard2: null, // 身份证反面文件信息
name: '', // 姓名 name: '', // 姓名
idNumber: '', // 身份证号 idNumber: '', // 身份证号
address: '', // 居住地址 address: '', // 居住地址
@ -40,26 +43,27 @@ Page({
*/ */
uploadImage(field) { uploadImage(field) {
const _this = this; const _this = this;
wx.chooseMedia({ wx.chooseImage({
count: 1, count: 1,
mediaType: ['image'],
sizeType: ['compressed'], sizeType: ['compressed'],
sourceType: ['album', 'camera'], sourceType: ['album', 'camera'],
success(res) { success: (res) => {
// 获取图片临时路径 const tempFilePaths = res.tempFilePaths;
const tempFilePaths = res.tempFiles;
if (tempFilePaths && tempFilePaths.length > 0) { if (tempFilePaths && tempFilePaths.length > 0) {
// 更新页面数据 // 更新页面数据
_this.setData({ _this.setData({
[field]: tempFilePaths[0].tempFilePath [field === 'idCardFront' ? 'idCardFront' : 'idCardBack']: tempFilePaths[0],
[field === 'idCardFront' ? 'idcard1' : 'idcard2']: {
path: tempFilePaths[0],
name: `身份证${field === 'idCardFront' ? '正面' : '反面'}_${new Date().getTime()}.jpg`
}
}); });
// 这里可以添加图片上传到服务器的逻辑
// 模拟识别成功后填充信息 // 模拟识别成功后填充信息
_this.simulateOcrResult(); _this.simulateOcrResult();
} }
}, },
fail(err) { fail: (err) => {
console.error('选择图片失败:', err); console.error('选择图片失败:', err);
wx.showToast({ wx.showToast({
title: '选择图片失败', title: '选择图片失败',
@ -83,10 +87,35 @@ Page({
}); });
}, },
/**
* 上传文件到服务器
*/
async uploadFileToServer(filePath, fileType) {
try {
console.log(`开始上传${fileType}文件:`, filePath);
const result = await API.uploadSettlementFile(filePath, fileType);
if (result && result.fileUrl) {
console.log(`${fileType}上传成功:`, result.fileUrl);
return result.fileUrl;
} else {
throw new Error(`${fileType}上传失败`);
}
} catch (error) {
console.error(`${fileType}上传失败:`, error);
wx.showToast({
title: `${fileType}上传失败`,
icon: 'none'
});
throw error;
}
},
/** /**
* 提交认证 * 提交认证
*/ */
submitAuth() { async submitAuth() {
// 验证是否上传了身份证 // 验证是否上传了身份证
if (!this.data.idCardFront || !this.data.idCardBack) { if (!this.data.idCardFront || !this.data.idCardBack) {
wx.showToast({ wx.showToast({
@ -96,23 +125,73 @@ Page({
return; return;
} }
// 这里可以添加提交认证信息到服务器的逻辑 // 检查用户是否已登录
wx.showLoading({ title: '提交中...' }); const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
if (!openid || !userId) {
wx.showToast({
title: '请先登录',
icon: 'none'
});
return;
}
wx.showLoading({ title: '正在上传文件...', mask: true });
try {
// 上传身份证正面
const idcard1Url = await this.uploadFileToServer(this.data.idcard1.path, 'idCardFront');
// 上传身份证反面
const idcard2Url = await this.uploadFileToServer(this.data.idcard2.path, 'idCardBack');
// 模拟提交成功 console.log('所有文件上传完成');
setTimeout(() => {
// 准备提交数据
const submitData = {
openid: openid,
userId: userId,
idcard1: idcard1Url,
idcard2: idcard2Url,
name: this.data.name,
idNumber: this.data.idNumber,
address: this.data.address
};
console.log('提交数据:', submitData);
// 调用后端API提交数据
const result = await API.request('/api/user/update', 'POST', submitData);
console.log('认证提交结果:', result);
if (result && result.success) {
wx.hideLoading();
wx.showToast({
title: '认证成功',
icon: 'success',
duration: 1500
});
// 延时返回上一页
setTimeout(() => {
this.navigateBack();
}, 1500);
} else {
wx.hideLoading();
wx.showToast({
title: result.message || '认证失败',
icon: 'none'
});
}
} catch (error) {
wx.hideLoading(); wx.hideLoading();
console.error('认证提交失败:', error);
wx.showToast({ wx.showToast({
title: '认证成功', title: '提交失败,请重试',
icon: 'success', icon: 'none'
duration: 1500
}); });
}
// 延时返回上一页
setTimeout(() => {
this.navigateBack();
}, 1500);
}, 1000);
}, },
/** /**

2
project.private.config.json

@ -1,6 +1,6 @@
{ {
"libVersion": "3.10.3", "libVersion": "3.10.3",
"projectname": "xcx22", "projectname": "wxxcx1",
"setting": { "setting": {
"urlCheck": false, "urlCheck": false,
"coverView": true, "coverView": true,

19
server-example/server-mysql.js

@ -1036,6 +1036,14 @@ User.init({
notice: { notice: {
type: DataTypes.STRING(255) // 通知提醒 type: DataTypes.STRING(255) // 通知提醒
}, },
idcard1: {
type: DataTypes.TEXT, // 身份证正面
comment: '身份证正面'
},
idcard2: {
type: DataTypes.TEXT, // 身份证反面
comment: '身份证反面'
},
// 时间字段 // 时间字段
created_at: { created_at: {
type: DataTypes.DATE, type: DataTypes.DATE,
@ -1576,9 +1584,16 @@ EggbarPost.init({
comment: '动态内容' comment: '动态内容'
}, },
images: { images: {
type: DataTypes.JSON, type: DataTypes.TEXT,
allowNull: true, allowNull: true,
comment: '图片URL数组' comment: '图片URL数组',
get() {
const value = this.getDataValue('images');
return value ? JSON.parse(value) : [];
},
set(value) {
this.setDataValue('images', JSON.stringify(value));
}
}, },
topic: { topic: {
type: DataTypes.STRING(255), type: DataTypes.STRING(255),

Loading…
Cancel
Save