前端vue+express实现文件的上传下载示例

新建server.js

yarn init -y
yarn add express nodemon -D
var express = require(\"express\");
const fs = require(\"fs\");
var path = require(\"path\");
const multer = require(\"multer\"); //指定路径的

var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 前端解决跨域问题
app.all(\"*\", (req, res, next) => {
  res.header(\"Access-Control-Allow-Origin\", \"*\");
  next();
});
// 访问静态资源
app.use(express.static(path.join(__dirname)));

// 文件上传
app.post(\"/upload\", multer({ dest: \"./public\" }).any(), (req, res) => {
  const { fieldname, originalname } = req.files[0];
  // 创建一个新路径
  const name = fieldname.slice(0, fieldname.indexOf(\".\"));
  const newName = \"public/\" + name + path.parse(originalname).ext;
  fs.rename(req.files[0].path, newName, function (err) {
    if (err) {
      res.send({ code: 0, msg: \"上传失败\", data: [] });
    } else {
      res.send({ code: 1, msg: \"上传成功\", data: newName });
    }
  });
});
// 文件下载
app.get(\'/download\', function(req, res) {
  res.download(\'./public/test.xls\');
});

// 图片下载
app.get(\'/download/img\', function(req, res) {
  res.download(\'./public/2.jpg\');
});

let port = 9527;
app.listen(port, () => console.log(`端口启动: http://localhost:${port}`));


(1):前端文件上传请求

第一种: form表单

  <form action=\"http://localhost:9527/upload\" method=\"POST\" encType=\"multipart/form-data\">
      <input type=\"file\" name=\"user\"/>
      <input type=\"submit\" />
    </form>

前端vue+express实现文件的上传下载示例

第一种: input输入框

   <input type=\"file\"  @change=\"changeHandler($event)\"/>
     changeHandler(event) {
      let files  = event.target.files[0];
      console.log(\"files\",files)
      let data = new FormData();
      data.append(files.name,files);
      console.log(\"data\",data)
      axios.post(\"http://localhost:9527/upload\",data,{
        headers:{
          \"Content-Type\":\"multipart/form-data\"
        }
      }).then(res =>{
        console.log(\"res\",res)
      })
    },

前端vue+express实现文件的上传下载示例

(2):前端文件下载

第一种: 后端返回一个下载的链接地址,前端直接使用 即可
第二种: 使用二进制流文件下载

    <input type=\"button\" value=\"点击下载\" @click=\"handleDownload\">
      handleDownload() {  
    axios({  
      method: \'get\',  
      url: \"http://localhost:9527/download\",  
      data: {    
        test: \"test data\"  
      },  
      responseType: \"arraybuffer\" // arraybuffer是js中提供处理二进制的接口
    }).then(response => {          
      // 用返回二进制数据创建一个Blob实例 
      if(!response) return;
      let blob = new Blob([response.data], {            
        type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\", 
      }) // for .xlsx files          
      // 通过URL.createObjectURL生成文件路径          
      let url = window.URL.createObjectURL(blob) 
      console.log(\"url==========\",url)        
      // 创建a标签          
      let ele = document.createElement(\"a\")          
      ele.style.display = \'none\'          
      // 设置href属性为文件路径,download属性可以设置文件名称          
      ele.href = url          
      ele.download = this.name          
      // 将a标签添加到页面并模拟点击          
      document.querySelectorAll(\"body\")[0].appendChild(ele)          
      ele.click()          
      // 移除a标签          
      ele.remove()        
    });
  },

前端vue+express实现文件的上传下载示例

(3) 附加:二进制流图片的下载

   // 二进制流图片文件的下载
  downLoadImg() {
     axios({
        method: \'get\',
        url: `http://localhost:9527/download/img`,
        responseType: \'arraybuffer\',
        params: {
          id: 12
        }
      }).then(res => {
        var src = \'data:image/jpg;base64,\' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), \'\'))
       // this.srcImg = src // 图片回显
        var a = document.createElement(\'a\')
        a.href = src
        a.download = \'2.jpg\'
        a.click()
        a.remove()
      })
    }

前端vue+express实现文件的上传下载示例

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容