将这个uniapp页面中的本地图片上传功能改为拍照上传功能和本地上传
时间: 2024-12-16 16:30:49 浏览: 5
uniapp多张图片上传.rar
要将现有的UniApp页面中的本地图片上传功能改为支持拍照上传和本地上传,你可以通过以下步骤进行修改:
### 1. 修改模板部分
在模板部分,使用 `u-camera` 组件来添加拍照上传功能,并保留原有的 `u-upload` 组件用于本地上传。
```html
<template>
<div class="container">
<div v-if="dataLoaded" class="form-container">
<!-- 表单部分 -->
<u-form @submit.prevent="updateData">
<div class="form-group">
<label for="DANGER_PIC">隐患图片:</label>
<img :src="editableData.DANGER_PIC" alt="隐患图片" class="danger-pic" />
</div>
<div class="form-group">
<label for="DANGER_GRADE">隐患等级:</label>
<input id="DANGER_GRADE" v-model="editableData.DANGER_GRADE" type="text" disabled />
</div>
<div class="form-group">
<label for="DANGER_DESC">隐患描述:</label>
<input id="DANGER_DESC" v-model="editableData.DANGER_DESC" type="text" disabled />
</div>
<div class="form-group">
<label for="CORRE_DDL">整改完成时间:</label>
<span>{{ currentDateTime }}</span>
</div>
<u-form-item class="upload" label="整改图片" prop="upload">
<u-upload
:fileList="fileList"
:previewFullImage="true"
@afterRead="afterRead"
@delete="deletePic"
:maxCount="1"
width="80"
height="80"
></u-upload>
<u-button type="primary" @click="takePhoto">拍照上传</u-button>
</u-form-item>
<!-- 提交按钮(如果需要修改数据,可以启用并提交) -->
<button type="submit" @click.prevent="handleSubmit" class="submit-button">保存</button>
</u-form>
</div>
</div>
</template>
```
### 2. 修改脚本部分
在脚本部分,添加 `takePhoto` 方法来调用相机拍照,并处理拍照后的图片。
```javascript
<script>
import request from '@/utils/request';
import { getToken } from '@/utils/auth';
export default {
data() {
return {
data: null,
editableData: {},
fileList: [],
dataLoaded: false,
selectedRecordId: null, // 用于存储从上一个页面传递的记录ID
};
},
methods: {
async afterRead(event) {
let lists = [].concat(event.file);
let fileListLen = this[`fileList${event.name}`].length;
lists.map((item) => {
this[`fileList${event.name}`].push({
...item,
status: 'uploading',
message: '上传中'
});
});
for (let i = 0; i < lists.length; i++) {
const result = await this.uploadFilePromise(lists[i].url);
let parsedResult = JSON.parse(result);
let item = this[`fileList${event.name}`][fileListLen];
this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: parsedResult.data
}));
fileListLen++;
}
console.log(this.fileList);
},
deletePic(e) {
this['fileList'].splice(0, 1);
},
uploadFilePromise(url) {
const header = { 'Authorization': `Bearer ${getToken()}` };
return new Promise((resolve, reject) => {
let a = uni.uploadFile({
url: 'http://10.118.50.18:8001/api/danger_rectify_record/upload', // 仅为示例,非真实的接口地址
filePath: url,
header: header,
name: 'fileinput',
success: (res) => {
resolve(res.data);
}
});
});
},
fetchData() {
const params = {
page: 1,
rows: 30,
sort: "DANGER_R_ID",
order: "desc",
wheres: JSON.stringify([
{ name: "ORDER_STATUS", value: "1" },
{ name: "DANGER_R_ID", value: this.selectedRecordId }
])
};
request({
url: '/api/danger_rectify_record/getPageData',
method: 'POST',
header: { 'content-type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
data: params,
dataType: 'json'
}).then(response => {
this.data = response;
if (this.data.rows.length > 0) {
this.editableData = { ...this.data.rows[0] };
}
this.dataLoaded = true;
}).catch(error => {
console.error(error);
uni.showToast({ title: '请求失败', icon: 'none' });
});
},
handleSubmit() {
console.log(this.editableData);
const mainData = {};
if (this.fileList.length != 0) {
mainData.CORRE_FINPIC = this.fileList[0].url;
}
if (this.editableData.CORRE_FINTIME !== '' || this.editableData.CORRE_FINTIME !== null) {
mainData.CORRE_FINTIME = this.editableData.CORRE_FINTIME;
} else if (this.editableData.CORRE_FINTIME == '' || this.editableData.CORRE_FINTIME == null) {
mainData.CORRE_FINTIME = '2024-11-15 09:50:32';
}
mainData.DANGER_R_ID = this.editableData.DANGER_R_ID;
mainData.ORDER_STATUS = 2;
console.log(mainData);
request({
url: '/api/Rectification/update',
method: 'POST',
header: { 'content-type': 'application/json', 'Authorization': `Bearer ${getToken()}` },
data: { mainData },
dataType: 'json'
}).then(response => {
console.log(response);
uni.showToast({ title: '更新成功', icon: 'success' });
}).catch(error => {
console.error(error);
uni.showToast({ title: '更新失败', icon: 'none' });
});
},
takePhoto() {
uni.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], // 只能选择拍照
success: (res) => {
const tempFilePaths = res.tempFilePaths;
this.afterRead({ file: [{ url: tempFilePaths[0] }] });
}
});
}
},
computed: {
formattedData() {
return this.data ? JSON.stringify(this.data, null, 2) : '';
},
currentDateTime() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
}
},
onLoad(options) {
this.selectedRecordId = options.recordId;
this.fetchData();
},
mounted() {
this.fetchData();
}
};
</script>
```
### 3. 修改样式部分
样式部分不需要做太大改动,保持现有样式即可。
```scss
<style lang="scss">
.container {
padding: 20px;
max-width: 600px;
margin: 0 auto;
}
.form-container {
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
}
.form-group {
display: flex;
align-items: center;
margin-bottom: 15px;
label {
width: 120px;
font-weight: bold;
margin-right: 10px;
}
input[type="text"] {
flex: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
span {
flex: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
}
.submit-button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
&:hover {
background-color: #0056b3;
}
}
</style>
```
这样,你就完成了将本地图片上传功能改为支持拍照上传和本地上传的功能。
阅读全文