微信小程序 上传图片跳转页面-接收数据并调用接口-重新识别图片

展示:

首页:home

下一页:scan

home.wxml:

 <view class="camera-icon" bindtap="openCamera">
      <image src="/static/images/icon/camera.png" mode="aspectFill" style="width:18px;height:18px;margin:0 0 0 2px" />
    </view>  

home.js:


    // 打开相册选择图片
    openCamera() {
      console.log("11111")
      wx.chooseImage({
        count: 1, // 限制选择 1 张图片
        sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
        sourceType: ['album', 'camera'], // 支持从相册或相机选择
        success: (res) => {
          const selectedImage = res.tempFilePaths[0]; // 获取选择的图片路径
          // 跳转到 scan 页面并传递图片路径
          wx.navigateTo({
            url: `/pages/scan/scan?imagePath=${encodeURIComponent(selectedImage)}`,
          });
        },
        fail: (err) => {
          console.log("选择图片失败", err);
        },
      });
    },

scan.wxml:

<view>


	<!-- 响应区域 -->
	<view class="response-container">
		<view class="image-container">
			<image src="{
   
   {imagePath}}" style="width: 100%;height:100%;" />
		</view>
		<view class="text-container">

		</view>
		<view bindtap="reupload" class="retry-button">
			<text>重新传图</text>
		</view>
	</view>

	<!-- 相关结果 -->
	<view wx:if="{
   
   {response}}" class="result-section">
		<view>相关结果:</view>
		<view wx:for="{
   
   {response.best_matches}}" wx:key="index">
			<image src="{
   
   {item.pic}}" />
			<text>{
   
   {item.image_name}}</text>
		</view>
	</view>

</view>

scan.js:

// 引用公共配置文件
const config = require('../../utils/config.js');

Page({
  data: {
    response: null, // 接收返回的数据
    imagePath: '',  // 默认图片路径
  },

  onLoad(options) {
    // 获取从上一个页面传递过来的参数
    if (options.imagePath) {
      this.setData({
        imagePath: decodeURIComponent(options.imagePath)  // 解码图片路径
      });

      // 如果图片路径存在,调用上传图片的方法
      this.uploadImage();
    } else {
      wx.showToast({
        title: '未选择图片',
        icon: 'none',
      });
    }
  },

  // 上传图片的方法
  uploadImage() {
    if (!this.data.imagePath) {
      wx.showToast({
        title: '图片路径不存在',
        icon: 'none',
      });
      return;
    }

    wx.showLoading({
      title: '加载中...',
    });

    wx.uploadFile({
      url: `${config.SCAN_URL}/find_match`, // 后端接口
      filePath: this.data.imagePath, // 需要上传的文件路径
      name: 'query_image', // 后端接收的字段名称
      formData: {
        additionalField: 'value', // 示例:传递额外的字段
      },
      success: (uploadRes) => {
        const data = JSON.parse(uploadRes.data); // 假设返回的数据是 JSON 格式

        // 为每个元素增加 pic 字段
        if (data && Array.isArray(data.best_matches)) {
          const newData = data.best_matches.map(item => ({
            ...item,
            pic: `${config.SCAN_URL}/api/${item.directory}/${item.file_name}`, // 拼接图片完整路径
          }));

          // 将修改后的数据更新到页面
          this.setData({
            response: {
              ...data,
              best_matches: newData, // 更新带有 pic 字段的数据
            },
          });
        } else {
          wx.showToast({
            title: '无匹配结果',
            icon: 'none',
          });
        }

        // 上传成功后隐藏加载中
        wx.hideLoading();
      },
      fail: (err) => {
        console.error('上传失败', err);

        // 上传失败后隐藏加载中
        wx.hideLoading();

        // 弹出提示信息
        wx.showToast({
          title: '上传失败,请重试',
          icon: 'none',
        });
      },
    });
  },

  // 点击重新上传图片
  reupload() {
    wx.chooseImage({
      count: 1, // 限制选择 1 张图片
      sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
      sourceType: ['album', 'camera'], // 支持从相册或相机选择
      success: (res) => {
        const selectedImage = res.tempFilePaths[0]; // 获取选择的图片路径
        this.setData({
          imagePath: selectedImage, // 更新图片路径
          response: null, // 清空之前的响应数据
        });
        this.uploadImage(); // 重新上传图片
      },
      fail: (err) => {
        console.log("选择图片失败", err);
      },
    });
  },
});

scan.wxss:

/* 上传区域 */
.upload-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-section {
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-btn {
  background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
  padding: 40px;
  border-radius: 10px;
  border: 2px dashed #007aff;
  display: inline-block;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;
}

.upload-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 16px;
  color: #007aff;
}

.image-preview {

  
}

.response-container {
  width: 100%;
  height: 100px;
  background-color: #2a2a2a;
  color: white;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.image-container {
  margin-left: 10px;
  margin-top: 40px;
  width: 100px;
  height: 100px;
  background-color: white;
  border: 1px solid #999;
}

.text-container {
  flex: 1;
  margin-left: 10px;
  margin-right: 20px;
  margin-top: 0px;
  height: 60px;
  overflow: hidden;
  white-space: normal;
  word-wrap: break-word;
}

.retry-button {
  text-align: center;
  font-size: 12px;
  margin-right: 10px;
}

.retry-icon {
  width: 40px;
  height: 40px;
}

.result-section {
  margin-top: 20px;
  padding: 10px;
}

.match-item {
  margin-top: 20px;
}

.match-item text {
  display: block;
  margin-bottom: 5px;
}