node+vue实现图片的上传和预览(multer中间件)
以下是使用Node.js, Vue.js和Multer中间件实现图片上传和预览的示例代码:
Node.js (Express) 端:
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, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage })
app.post('/upload', upload.single('image'), (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).send('No file uploaded.');
}
res.send(file.path); // 返回上传文件的路径
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Vue.js 端:
<template>
<div>
<input type="file" @change="previewImage" />
<img v-if="imageUrl" :src="imageUrl" alt="Image preview" />
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: null
};
},
methods: {
async previewImage(event) {
const image = event.target.files[0];
const formData = new FormData();
formData.append('image', image);
try {
const response = await fetch('http://localhost:3000/upload', {
method: 'POST',
body: formData
});
const imagePath = await response.text();
this.imageUrl = URL.createObjectURL(image);
console.log('Image uploaded and path received:', imagePath);
} catch (error) {
console.error('Error uploading image:', error);
}
}
}
};
</script>
确保您已经安装了express和multer。
npm install express multer
此代码实现了图片的上传和预览功能。用户在Vue.js前端选择图片后,会通过FormData发送到Node.js服务器。服务器端使用multer中间件处理上传的文件,并返回文件的保存路径。Vue.js前端获取到这个路径后,可以用URL.createObjectURL
方法创建一个可以在<img>
标签中使用的URL,实现图片的预览。
评论已关闭