*后端*
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;
fs.rename(file.path,newName,(err)=>{
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">
<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('服务器繁忙,请稍后重试!');
})
},