冲刺记录6
今日任务:将相机照出的图片显示到主界面上
遇到困难:和之前一样,测试很浪费时间
<button @click="capturePhoto" class="btn camera-btn">拍照</button>
<button @click="getCurrentLocation" class="btn location-btn">定位</button>
<button @click="recognizePhoto" class="btn recognition-btn">识别</button> <!-- 新增的识别按钮 -->
<button @click="addIncomeRecord" class="btn income-btn">保存</button>
<button @click="handleClick" class="btn s-btn">上传</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
place: '',
remark: '',
photo: null,
baiduClientId: 'KJgBtX35dMQI8CMRtbFDOISY',
baiduClientSecret: 'gXf9g10ktcElz66CLToG28MOCuclRqIV',
accessToken: null,
backgroundImage: '/static/111.jpg' // 背景图片的 URL
};
},
methods: {
addIncomeRecord() {
if (!this.place) {
uni.showToast({
title: '请输入地点',
icon: 'none'
});
return;
}
const record = {
type: 'income',
place: this.place,
date: new Date().toISOString().substr(0, 10),
remark: this.remark || '无备注',
photo: this.photo
};
this.saveRecord(record);
},
async handleClick() {
try {
// 使用fetch API发送POST请求
const response = await fetch('http://192.168.1.176:8081/book', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.inputValue,
date:new Date().toISOString().substr(0, 10),
place:this.place,
remark:this.remark,
photo: this.photo,
}) // 传递输入框的值,并去除首尾空格
});
// 检查响应状态码
if (response.ok) {
// 请求成功处理
const data = await response.json(); // 解析响应数据
console.log(data); // 输出后端返回的数据
this.saveRecord(data);
alert('写入成功!'); // 弹出成功提示
} else {
// 请求失败处理
console.error('写入失败:', response.statusText); // 输出错误信息
alert('写入失败,请稍后重试!'); // 弹出错误提示
}
} catch (error) {
// 捕获异常并处理
console.error('请求失败:', error); // 输出错误信息
alert('请求失败,请稍后重试!'); // 弹出错误提示
}
},
saveRecord(record) {
let records = uni.getStorageSync('records') || [];
records.push(record);
uni.setStorageSync('records', records);
uni.showToast({
title: '记录添加成功',
icon: 'success'
});
this.resetForm();
},
resetForm() {
this.place = '';
this.remark = '';
this.photo = null;
this.loadRecords();
},
capturePhoto() {
uni.chooseImage({
count: 1,
sourceType: ['camera'],
success: (res) => {
const tempFilePath = res.tempFilePaths[0];
uni.request({
url: tempFilePath,
method: 'GET',
responseType: 'arraybuffer',
success: (response) => {
const base64Image = 'data:image/jpeg;base64,' + uni
.arrayBufferToBase64(response.data);
this.photo = base64Image;
},
fail: (err) => {
console.error('获取图片失败:', err);
uni.showToast({
title: '获取图片失败',
icon: 'none'
});
}
});
},
fail: (err) => {
console.error('选择图片失败:', err);
uni.showToast({
title: '选择图片失败',
icon: 'none'
});
}
});
},