歡迎您光臨本站 註冊首頁

node+vue實現文件上傳功能

←手機掃碼閱讀     niceskyabc @ 2020-06-06 , reply:0

本文實例為大家分享了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('服務器繁忙,請稍後重試!');    })    },

[niceskyabc ] node+vue實現文件上傳功能已經有289次圍觀

http://coctec.com/docs/vue-js/show-post-237202.html