首页 > 代码库 > vue + multer 上传图片
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 上传图片
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。