javascript – 从Koa中的POST请求下载文件

我正在尝试使用koa-router从Koa中的POST请求处理程序触发下载.基本上,我正在尝试做这样的事情:

app.js

const Koa = require('koa')
const router = require('./router')

const app = new Koa()

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000)

router.js

const fs = require('fs')
const Router = require('koa-router')

const router = new Router()

router.post('/generate',function * () {
  const path = `${__dirname}/test.txt`
  this.body = fs.createReadStream(path)
  this.set('Content-disposition','attachment; filename= test.txt')
})

module.exports = router

client.js

const { fetch } = window;

const request = {
  method: 'POST',body: JSON.stringify({ fake: 'data' })
}

// Make the POST request
fetch('/generate',request)

但是,发送POST请求时,没有任何反应.我也没有在服务器控制台或浏览器控制台中收到任何错误.任何帮助,将不胜感激!

解决方法

您可以尝试使用 https://github.com/koajs/send
router.post('/generate',function * (next) {
    yield send(this,'file.txt');
});

在客户端,您需要在通过邮件请求接收文件内容时创建并触发下载.将此代码放在请求回调中

fetch('/generate',request)
  .then(res => { return res.text() })
  .then(content => {

    uriContent = "data:application/octet-stream," + encodeURIComponent(content);

    newWindow = window.open(uriContent,'somefile');

  });

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...