如何从 CycleJS 中的 POST 请求中获取文件

How get file from POST request in CycleJS

我写了一个 Spring 控制器,接受 json 请求并响应 pdf 文件。

public ResponseEntity<byte[]> generateResp(...)
     byte[] gMapRep = Files.readAllBytes(file.toPath());

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.parseMediaType("application/pdf"));

            httpHeaders.setContentDispositionFormData("content-disposition", "filename=report.pdf");
            httpHeaders.setCacheControl("must-relative, post-check=0, pre-check=0");

        return ResponseEntity
                .ok()
                .headers(httpHeaders)
                .body(gMapRep);

在 Postman 上运行良好。 POST 方法不需要,因为我需要发送一些参数。但是我怎样才能从响应中 get/download CycleJS 中的 pdf 文件。我在前端试过:

const buttonRequest$ = actions.buttonClick$
        .withLatestFrom(sources.arcgisDriver.onMapLoaded,
            (ev, _)=> {
                return {
                    url: myURL,
                    method: 'POST',
                    type: 'application/json',
                    send: data
                }
            });

    sources.HTTP
        .filter(response => {
            return !response.error && response.request.url.includes(myURL)
        })
        .subscribe(resp => window.open("data:application/pdf;base64, " + resp.text, '', 'height=650,width=840'));

这是一个 客户端 Cycle.js using RxJS 示例,它从(模拟的)API 中获取值,然后单击按钮填充隐藏表单,然后提交服务器脚本的表单 returns 指向新浏览器的 PDF 文档 window 或选项卡:

import Rx from 'rx';
import Cycle from '@cycle/core';
import {div, form, input, button, makeDOMDriver} from '@cycle/dom';

function makeFormDriver (formid, elemid) {
  return function (post$) {
    post$.subscribeOnNext(function (post) {
        document.querySelector(elemid).value = post;
        document.querySelector(formid).submit();
    });
  }
}

function main({DOM}) {
  const buttonClick$ = DOM.select('button#pdf').events('click');
  const api$ = Rx.Observable.of('test.pdf'); // mocked API
  const post$ = buttonClick$.withLatestFrom(api$, (bclick, file) => file);

  const vdom$ = Rx.Observable.of(
    div([
      form('#pdfform', {
        method: 'post', action: 'http://localhost:3000/file',
        target: '_blank', style: 'display: none;'
      }, [input(#filename', {type: 'hidden', name: 'filename'})]),
      button('#pdf', 'PDF')
    ])
  );

  return {
    DOM: vdom$,
    FORM: post$
  };
}

Cycle.run(main, {
  DOM: CycleDOM.makeDOMDriver('#app'),
  FORM: makeFormDriver('#pdfform', '#filename')
});

这是一个 客户端 Cycle.js using xstream 示例:

import xs from 'xstream';
import Cycle from '@cycle/xstream-run';
import {div, form, input, button, makeDOMDriver} from '@cycle/dom';

function makeFormDriver (formId, elemId) {
  const form = document.querySelector(formId);
  const elem = document.querySelector(elemId);
  return function (post$) {
    post$.addListener({
      next: function (post) {
        elem.value = post;      // populate form data
        form.submit();          // submit form
      },
      error: function () {},
      complete: function () {}
    });
  }
}

function main(sources) {
  const buttonclick$ = sources.DOM.select('#pdfbutton').events('click');
  const api$ = xs.of('test.pdf');                           // mocked API
  const post$ = buttonclick$.map(bclick => api$).flatten(); // ~ withLatestFrom

  let vtree$ = xs.of(
    div('.pdf', [
      form('#pdfform', {attrs: {
        method: 'post', action: '/file',
        target: '_blank', style: 'display: none;'      // new tab and hide form
      }}, [
        input('#filename', {attrs: {name: 'filename', type: 'input'}}),
      ]),
      button('#pdfbutton', 'view pdf')
    ])
  )

  return {
    DOM: vtree$,
    FORM: post$
  };
}

Cycle.run(main, {
  DOM: makeDOMDriver('.app-container'),
  FORM: makeFormDriver('#pdfform', '#filename')
});

这里有一个 服务器端 Cycle.js and xstream example using Express 接收 POST 数据并返回指定文档:

import xs from 'xstream';
import Cycle from '@cycle/xstream-run';
import express from 'express';
import bodyParser from 'body-parser';

let server = express();
server.use(bodyParser.urlencoded({ extended: false }))

function makeDownloadDriver (effect) {
  return function (postfile$) {
    let file$ = postfile$.map(body => body.filename)
    file$.addListener({
      next: effect,
      error: function () {},
      complete: function () {}
    })
  }
}

server.use(function (req, res) {

  let postfile$ = xs.of(req)
    .filter(req => 'POST' === req.method && '/file' === req.url)
    .map(req => req.body);

  function main (sources) {
    return {
      postfile: postfile$
    };
  }

  Cycle.run(main, {
    postfile: makeDownloadDriver(file => res.sendFile(file, {root: __dirname})),
  });

});

server.listen(3000);

要查看它们与页面路由器一起工作,请查看 cycle-isomorphic-file-download