本文实例为大家分享了node+vue实现文件上传的具体代码,供大家参考,具体内容如下
*后端*
const express = require('express');
const router = express.router();
const multer = require('multer');
const fs = require('fs');
const pathlib = require('path');
const videomodel = require('../../models/my_yx_app/video');
//设置 视频文件存放位置
const uploadvido = multer({
dest:'uploads_yx_app/video/'
});
//上传视频
router.post('/uploadvideo',uploadvido.single('file'),(req,res)=>{
if (req.file) {
let file = req.file;
let newname = file.path+pathlib.parse(file.originalname).ext; //修改path
fs.rename(file.path,newname,(err)=>{ //修改path
if (err) {
return res.status(200).json({
code:0,
msg:'服务器繁忙!'
})
}else {
return res.status(200).json({
code:1,
msg:'上传完成',
title:pathlib.parse(file.originalname).name,
videourl:'http://127.0.0.1:3001/uploads_yx_app/video/'+file.filename+pathlib.parse(file.originalname).ext
})
}
})
}else {
return res.status(200).json({
code:0,
msg:'服务器繁忙!'
})
}
});
*前端*
<div class="from-contral" style="position: relative">
<!--此处name 与 uploadvido.single('file') 相同-->
<input type="file" name="file" @change="changefile" class="customstyle">
<el-button size="mini" type="primary">
添加文件
<i class="el-icon-upload el-icon--right"></i>
</el-button>
<div class="zt-title-video">{{ file.name }}</div>
<div class="zt-progress" v-show="percentageshow">
<el-progress
:text-inside="true"
:stroke-width="20"
:percentage="percentage"
>
</el-progress>
</div>
</div>
*js处理逻辑数据*
savedata() { //上传
let that = this;
let fd = new formdata();
fd.append('file', this.file);
fileupdata({ //上传文件存储在后端
method: 'post',
url: '/uploadvideo',
data: fd,
//监听上传时间 //实现进度条
onuploadprogress(progressevent) {
that.percentageshow = true;
that.percentage = parseint(((progressevent.loaded / progressevent.total) * 100));
}
}).then(res => {
if (res.data.code === 1) {
//数据持久化
fileupdata({
method: 'post',
url: '/savevideoinfo',
data: {
videourl: res.data.videourl, //路径
videoname: res.data.title, //标题
videotype:that.videotype, //类型
username:localstorage.getitem('username') //那个用户上传的
}
}).then(res => {
if (res.data.code === 1) {
settimeout(function () { //为什么延迟,为了使进度条走完
that.$message({
message: '上传成功',
type: 'success'
})
}, 1000);
}
}).catch(err => {
this.$message.error('服务器繁忙,请稍后重试!');
});
}
}).catch(err => {
this.$message.error('服务器繁忙,请稍后重试!');
})
},
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
我乃观音坐下的第一个男人