栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

node+vue实现文件上传功能

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

node+vue实现文件上传功能

本文实例为大家分享了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:'服务器繁忙!'
 })
 }
});

*前端*



   
   
   
   添加文件
   
   
   {{ file.name }}
   
   
  
 

*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('服务器繁忙,请稍后重试!');
  })
  },

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/70153.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号