文章目录
- 微信小程序字符串
- 字符串模板
- 字符串拼接
 
- 上传图片
- 编写JS代码
- 编写wxml代码
- 编写wxss代码
 
- GET请求测试
- 编写测试代码
- 域名不合法问题
 
- GET和POST请求测试
- 编写JS代码
- 编写wxml代码
- 编写wxss代码
 
- 效果展示
微信小程序字符串
字符串模板
这是ES6引入的特性,允许你通过反引号(`)创建模板字符串,并在其中嵌入变量或表达式。
let name = 'Alice';
let age = 25;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);  // 输出: My name is Alice and I am 25 years old.
字符串拼接
通过加号(+)将多个字符串和变量拼接在一起。
let name = 'Alice';
let age = 25;
let message = 'My name is ' + name + ' and I am ' + age + ' years old.';
console.log(message);  // 输出: My name is Alice and I am 25 years old.
上传图片
图像数据,base64编码,要求base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式 注意请去掉头部
媒体 / 图片 / wx.chooseImage(弃用)
 媒体 / 视频 / wx.chooseMedia
 文件 / FileSystemManager / FileSystemManager.readFile
编写JS代码
// index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imagePaths: [], // 用于存储图片路径的数组
    imageBase64: '', // 用于存储图片转换成的Base64编码
  },
  // 按钮点击事件处理函数
  chooseAndUploadImage: async function () {
    try {
      //刷新数据
      this.setData({
        imagePaths: [],
        imageBase64:'',
        imageClassification:{}
      });
      // 图片上传
      const getImageInfo = await this.uploadImage();
      console.log('图片上传成功', getImageInfo.tempFiles);
      this.setData({
        imagePaths: [getImageInfo.tempFiles[0].tempFilePath]
      });
      // 编码转换
      const getBase64 = await this.convertToBase64(getImageInfo.tempFiles[0].tempFilePath);
      console.log('转换Base64编码成功!');
      // console.log('编码转换成功', getBase64.data);
      this.setData({
        imageBase64: getBase64.data
      });
      // console.log('页面Base64编码参数值:', this.data.imageBase64);
    } catch (error) {
      // 处理错误
      console.error('图片上传操作失败:', error);
      // 可以给用户一个错误提示
      // wx.showToast({ title: '请求失败', icon: 'none' });
    }
  },
  uploadImage: function () {
    return new Promise((resolve, reject) => {
      // 选择图片
      wx.chooseMedia({
        count: 1, // 允许选择的图片数量
        mediaType: ['image'], // 文件类型
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
        sizeType: ['original', 'compressed'], // 是否压缩所选文件,基础库2.25.0前仅对 mediaType 为 image 时有效,2.25.0及以后对全量 mediaType 有效 
        camera: 'back', // 仅在 sourceType 为 camera 时生效,使用前置或后置摄像头
        success(res) {
          resolve(res)
          // 上传成功后的回调
          // console.log('上传成功', res.tempFiles); // 这里可以处理服务器返回的数据
          // console.log(res.tempFiles[0].tempFilePath)
          // console.log(res.tempFiles[0].size)
        },
        fail(err) {
          reject(err);
          // 选择图片失败后的回调
          console.error('选择图片失败', err);
        }
      });
    });
  },
  // 图片转base64编码函数
  convertToBase64: function (filePath) {
    return new Promise((resolve, reject) => {
      const fs = wx.getFileSystemManager();
      fs.readFile({
        filePath: filePath,
        encoding: 'base64',
        success(res) {
          // const base64Data = 'data:image/png;base64,' + res.data; // 注意:这里假设图片是png格式,你需要根据实际情况修改MIME类型
          resolve(res);
        },
        fail(err) {
          reject(err);
        }
      });
    });
  }
})
编写wxml代码
<!--pages/index/index.wxml-->
<view class="disease">
  <button bindtap="chooseAndUploadImage">选择图片</button>
  <block wx:if="{{imagePaths.length > 0}}">
    <!-- <image src="{{imagePaths[0]}}" mode="widthFix" style="width: 100%;"></image> -->
    <image class="fixed-image" src="{{imagePaths[0]}}" mode="aspectFit"></image>
  </block>
  <block wx:else>
    <text>没有选择图片</text>
  </block>
</view>
编写wxss代码
/* 疾病图片样式 */
.disease {
  text-align: center;
  padding: 20px;
}
.fixed-image {
  width: 100%; /* 宽度设为100% */
  height: 300px; /* 你可以根据需要调整高度 */
  object-fit: cover; /* 确保图片按比例缩放并填充容器 */
  display: block; /* 移除图片下方的默认间隙 */
  margin: 0 auto; /* 居中显示 */
}
GET请求测试
编写测试代码
在页面的JS文件中写入如下代码:
// 假设这是一个页面(page)的 JS 文件
Page({
  data: {
    responseData: {}  // 用于存储服务器返回的响应数据
  },
  // 按钮点击事件,触发 POST 请求
  handleButtonClick: function() {
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=替换为你的API_KEY&client_secret=替换为你的SECRET_KEY',  // 请求的 URL
      method: 'GET',  // 指定请求方法为 GET
      header: {  // 根据服务器要求设置请求头
        'content-type': 'application/json'
      },
      success: (res) => {
        // 请求成功时执行的回调函数
        console.log('请求成功', res.data);
        this.setData({
          responseData: res.data  // 将响应数据存储在页面的 data 中
        });
      },
      fail: (error) => {
        // 请求失败时执行的回调函数
        console.error('请求失败', error);
      }
    });
  }
});
在 WXML 文件中添加一个按钮:
<!-- 假设这是页面的 WXML 文件 -->
<view>
  <button bindtap="handleButtonClick">发送 POST 请求</button>
  <view>
    <!-- 显示服务器返回的响应数据 -->
    <text>{{responseData['refresh_token']}}</text>
  </view>
</view>
域名不合法问题

 解决方案
 请参考文档:基础能力 / 网络 / 使用说明
 网页登录微信小程序管理后台,【管理->开发管理->服务器域名->修改】,添加域名即可。
 
 微信开发者工具,【详情->项目配置->域名信息】,显示新增的域名说明添加成功。
 
GET和POST请求测试
GET请求的返参作为POST请求的入参
编写JS代码
// index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    apiKey: '替换成你的',
    secretKey: '替换成你的',
    accessToken: '', // 用于存储服务器返回的access_token值
    imagePaths: [], // 用于存储图片路径的数组
    imageBase64: '', // 用于存储图片转换成的Base64编码
    imageClassification: {} // 用于存储图像分类结果
  },
  // 假设这是某个事件处理函数,比如按钮点击事件
  handleButtonClick: async function () {
    try {
      // 判断图片转换编码是否为空,为空就直接返回
      if (this.data.imageBase64 === '') {
        console.log('imageBase64 为空');
        return 0
      } else {
        console.log('执行其他操作');
        // 执行其他操作
      }
      // 发起GET请求
      const getResult = await this.getAccessToken();
      console.log('AccessToken请求成功!', getResult.data);
      this.setData({
        accessToken: getResult.data.access_token
      });
      console.log('AccessToken参数值:', this.data.accessToken);
      // // 从GET请求的响应中提取需要的数据
      // const neededData = getResult.data.access_token; // 假设someKey是你需要的字段
      // 使用GET请求的返回值作为POST请求的参数
      const postResult = await this.postImageClassification();
      // 处理POST请求的响应
      console.log('疾病诊断POST请求成功!', postResult.data);
      this.setData({
        imageClassification: postResult.data.results
      });
      console.log('疾病诊断结果:', this.data.imageClassification);
    } catch (error) {
      // 处理错误
      console.error('疾病诊断请求失败:', error);
      // 可以给用户一个错误提示
      // wx.showToast({ title: '请求失败', icon: 'none' });
    }
  },
  // 封装GET请求的函数
  getAccessToken: function () {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${this.data.apiKey}&client_secret=${this.data.secretKey}`, // GET请求的URL
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res); // 解析Promise为成功状态,并传递响应数据
          } else {
            reject(new Error(`GET请求失败,状态码:${res.statusCode}`)); // 解析Promise为失败状态,并传递错误信息
          }
        },
        fail: (err) => {
          reject(err); // 网络错误或其他错误时解析Promise为失败状态
        }
      });
    });
  },
  // 封装POST请求的函数
  postImageClassification: function () {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/pifubingzhenduan?access_token=${this.data.accessToken}`, // POST请求的URL
        method: 'POST',
        data: {
          image: this.data.imageBase64 // 将GET请求的返回值作为POST请求的参数
        },
        header: {
          'content-type': 'application/json' // 根据需要设置请求头
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res); // 解析Promise为成功状态,并传递响应数据
          } else {
            reject(new Error(`POST请求失败,状态码:${res.statusCode}`)); // 解析Promise为失败状态,并传递错误信息
          }
        },
        fail: (err) => {
          reject(err); // 网络错误或其他错误时解析Promise为失败状态
        }
      });
    });
  }
})
编写wxml代码
<!-- 诊断 -->
<view class="diagnosis">
  <button bindtap="handleButtonClick">疾病诊断</button>
  <view class="table">
    <block wx:for="{{imageClassification}}" wx:key="index">
      <view class="table-row">
        <view class="table-cell">{{item.name}}</view> 
        <view class="table-cell">{{item.score}}</view>
      </view>
    </block>
  </view>
</view>
编写wxss代码
/* 诊断样式 */
.diagnosis {
  padding: 20px;
}
.table {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.table-row {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px; /* 根据需要调整行间距 */
}
.table-cell {
  flex: 1; /* 使两列平分宽度 */
  padding: 10px; /* 根据需要调整单元格内边距 */
  box-sizing: border-box; /* 确保内边距不影响总宽度 */
  border: 1px solid #ddd; /* 可选:添加边框 */
  text-align: center; /* 可选:文本居中 */
}
效果展示
界面效果

 识别效果









![[Pro Git#3] 远程仓库 | ssh key | .gitignore配置](https://i-blog.csdnimg.cn/img_convert/e8c25a7d2f78980fe64c7c5feb79d1f2.png)










