uniapp壁纸小程序学习

y一个简单的图片上传云端的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<template>
<view class="container">
<!-- 预览图片 -->
<image :src="previewImage" mode="aspectFill" v-if="previewImage" @tap="preview"></image>
<!-- 上传图片按钮 -->
<view class="upload-btn" @tap="chooseImage">
上传图片
</view>
</view>
</template>

<script>
export default {
data() {
return {
previewImage: '' // 用于存储预览图片的URL
};
},
methods: {
chooseImage() {
// 选择图片
uni.chooseImage({
count: 1, // 允许选择的图片数量
sizeType: ['original', 'compressed'], // 可选择原图或压缩图
sourceType: ['album', 'camera'], // 可从相册选择或使用相机拍照
success: (res) => {
this.previewImage = res.tempFilePaths[0]; // 将选择的图片设置为预览图片
this.uploadImage(res.tempFilePaths[0]); // 上传选择的图片
}
});
},
preview() {
// 预览图片
uni.previewImage({
current: this.previewImage, // 当前预览的图片
urls: [this.previewImage] // 预览图片的URL列表
});
},
async uploadImage(tempPath) {
// 上传图片
const cloudPath = `images/${Date.now()}_${Math.floor(Math.random() * 1000)}.jpg`; // 生成图片的云端路径

try {
const result = await uniCloud.uploadFile({
cloudPath, // 云端路径
filePath: tempPath // 文件路径
});

console.log('图片上传成功', result); // 输出上传成功的信息
// 如果需要,你可以在这里更新数据库或其他操作
} catch (error) {
console.error('图片上传失败', error); // 输出上传失败的错误信息
}
}
}
};
</script>

<style>

.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%
}


.upload-btn {
width: 200px;
height: 50px;
line-height: 50px;
text-align: center;
background-color: #1aad19;
color: #fff;
margin-top: 20px;
}
</style>