使用vue实现一个图片上传的页面
时间: 2024-02-17 15:02:31 浏览: 119
好的,以下是用 Vue 实现一个图片上传页面的基本步骤:
1. 在 Vue 项目中安装 axios 和 element-ui:
```bash
npm install axios element-ui --save
```
2. 在组件中引入 element-ui 的上传组件和 axios:
```javascript
<template>
<div>
<el-upload
class="upload-demo"
:action="uploadUrl"
:on-preview="handlePreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:file-list="fileList"
:auto-upload="false"
:show-file-list="false"
multiple>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'ImageUpload',
data() {
return {
fileList: [],
uploadUrl: '/api/upload' // 上传图片的接口地址
}
},
methods: {
handlePreview(file) {
console.log(file)
},
handleRemove(file, fileList) {
console.log(file, fileList)
},
handleSuccess(response, file, fileList) {
console.log(response, file, fileList)
},
submitUpload() {
this.$refs.upload.submit()
}
}
}
</script>
```
3. 在组件中实现上传图片的方法:
```javascript
handleSuccess(response, file, fileList) {
console.log(response, file, fileList)
// 将上传成功的图片添加到 fileList 中
this.fileList.push({
name: response.data.fileName,
url: response.data.fileUrl
})
},
submitUpload() {
const formData = new FormData()
// 添加要上传的图片到 formData 中
this.fileList.forEach(file => {
formData.append('file', file.raw)
})
// 使用 axios 发送 POST 请求上传图片
axios.post(this.uploadUrl, formData).then(response => {
console.log(response)
}).catch(error => {
console.log(error)
})
}
```
4. 在服务端实现上传图片的接口:
```javascript
const express = require('express')
const multer = require('multer')
const path = require('path')
const app = express()
// 设置上传文件的存储路径和文件名
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
}
})
// 上传文件的限制
const limits = {
fileSize: 1024 * 500, // 500kb
files: 1
}
// 创建 multer 实例
const upload = multer({ storage, limits })
// 处理上传文件的 POST 请求
app.post('/api/upload', upload.single('file'), (req, res) => {
console.log(req.file)
res.json({
status: 'success',
data: {
fileName: req.file.filename,
fileUrl: `/uploads/${req.file.filename}`
}
})
})
// 启动服务
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000')
})
```
以上就是用 Vue 实现图片上传页面的基本步骤,你可以根据自己的实际需求进行修改和完善。
阅读全文