uniapp头像上传代码
时间: 2023-08-26 11:07:08 浏览: 65
以下是uniapp头像上传的示例代码:
1. 在需要上传头像的页面中,添加以下代码:
```
<template>
<div>
<img :src="imageUrl" alt="头像">
<input type="file" accept="image/*" @change="uploadImage">
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: '' // 头像地址
}
},
methods: {
// 上传头像
uploadImage(event) {
const file = event.target.files[0]
const formData = new FormData()
formData.append('file', file)
uni.request({
url: 'https://example.com/upload', // 上传接口地址
method: 'POST',
header: {
'content-type': 'multipart/form-data'
},
data: formData,
success: (res) => {
this.imageUrl = res.data.url // 上传成功后,将头像地址赋值给imageUrl
}
})
}
}
}
</script>
```
2. 在服务器端,需要处理上传的文件并返回对应的头像地址。以下是使用Node.js的示例代码:
```
const express = require('express')
const multer = require('multer')
const app = express()
const upload = multer({ dest: 'uploads/' }) // 上传文件存储路径
app.post('/upload', upload.single('file'), (req, res) => {
const file = req.file
const url = `https://example.com/uploads/${file.filename}` // 头像地址,需要根据实际情况修改
res.json({ url })
})
app.listen(3000, () => {
console.log('Server started on port 3000')
})
```
以上代码仅供参考,实际使用时需要根据自己的需求进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)