vue上传图片到服务器
时间: 2023-10-11 16:05:15 浏览: 120
可以使用axios库来发送POST请求,将图片转换成base64编码后发送到服务器。服务器接收到请求后,解码图片并保存。以下是一个简单的示例代码:
```
<template>
<div>
<input type="file" @change="handleFileUpload">
<button @click="uploadImage">上传图片</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
imageUrl: '',
};
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0];
},
uploadImage() {
let reader = new FileReader();
reader.readAsDataURL(this.file);
reader.onload = (event) => {
let base64 = event.target.result;
axios.post('/upload/image', { image: base64 }).then((response) => {
this.imageUrl = response.data.imageUrl;
});
};
},
},
};
</script>
```
在服务器端,可以使用Node.js的Express框架来接收请求,使用body-parser中间件来解析请求体,使用fs模块来保存图片。以下是一个简单的示例代码:
```
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const app = express();
app.use(bodyParser.json());
app.post('/upload/image', (req, res) => {
let base64 = req.body.image.replace(/^data:image\/\w+;base64,/, '');
let buffer = Buffer.from(base64, 'base64');
let fileName = 'image-' + new Date().getTime() + '.png';
fs.writeFile(fileName, buffer, (err) => {
if (err) {
console.log(err);
res.sendStatus(500);
} else {
res.send({ imageUrl: fileName });
}
});
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
阅读全文