vue + multer 上传图片
Posted monica_guorong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue + multer 上传图片相关的知识,希望对你有一定的参考价值。
vuejs(element-ui) + express (multer)上传文件
1.npm install multer --save
2. 新建vue文件
主要代码:
<form method="POST" enctype="multipart/form-data" class="form-horizontal" @submit.prevent="submit" ref="inputUpload">
<input type="file" name="resourceName" accept="audio/mpeg,image/png,image/jpeg" style="display:inline-block;width:250px;"
v-on:change="getFileInfo" />
<div slot="tip" class="el-upload_tip">Only .mp3, .png and .jpg file can be uploaded and size limit is 10MB.</div>
<el-button native-type="submit" class="el-icon-upload" :disabled="!formatFile">upload</el-button>
</form>
getFileInfo: function (event) {
if (event.target.files && event.target.files.length) {
this.upFile = event.target.files[0];
//主要读取file 显示一些信息
//....
submit: function (event) {
var self = this;
var fd = new FormData(event.target);
fetch(‘/uploadResource‘, {
method: ‘POST‘,
body: fd,
credentials: "include"
}).then(response => {//....})
}
3. fetch里面的url (读取文件存放到指定的目录下面)
var fs = require(‘fs‘)
var multer = require(‘multer‘)
var path = "./public/static/upload";
// if (!fs.existsSync(path)) {
// fs.mkdirSync(path)
// }
var storage = multer.diskStorage({
destination: function (req, res, cb) {
cb(null, path);
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({
storage: storage,
limits: {
fieldNameSize: ‘10M‘
}
})
exports.singleUpload = function (req, res) {
s = uploadResource.single(‘imgUpload‘);
s(req, res, function (err) {
if (err) {
res.send({
‘status‘: ‘failed‘
})
} else {
res.send({
‘status‘: ‘ok‘
})
}
})
}
4. api增加到router
router.post(‘/getFile‘,upload.singleUpload)
其他补充:如果是excel 换成
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
api里面解析的时候 用到 var xlsx = require(‘xlsx‘);//自己了解
以上是关于vue + multer 上传图片的主要内容,如果未能解决你的问题,请参考以下文章
javascript Multer上传图片(NodeJS Express)
上传图片,然后使用 Multer 和 Express.js 进行更新