vueh5上传图片
时间: 2023-07-26 19:08:27 浏览: 103
H5图片上传
你可以使用HTML5的File API和XMLHttpRequest对象来上传图片。以下是一个简单的示例:
1. 在Vue组件中添加一个input标签并设置type为file。
```html
<template>
<div>
<input type="file" @change="uploadImage">
</div>
</template>
```
2. 在Vue组件的methods中定义uploadImage方法,该方法将调用File API来获取选定的文件,并使用XMLHttpRequest对象将其上传到服务器。
```javascript
methods: {
uploadImage(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('image', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/image');
xhr.onload = () => {
if (xhr.status === 200) {
console.log('Image uploaded successfully!');
} else {
console.error('Failed to upload image.');
}
};
xhr.send(formData);
}
}
```
3. 在服务器端接收上传的文件并将其保存到服务器上的某个位置。
```javascript
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: 'uploads/' });
app.post('/upload/image', upload.single('image'), (req, res) => {
console.log(req.file); // { fieldname: 'image', originalname: 'example.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: 'uploads/', filename: 'f3b2e66a1b8ebe6d3d57f28b3688c5a8', path: 'uploads/f3b2e66a1b8ebe6d3d57f28b3688c5a8', size: 92976 }
res.send('Image uploaded successfully!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
```
以上示例仅供参考,具体实现可能因应用场景而有所不同。
阅读全文