2

I have write a Spring controller that takes json in request and responds pdf file.

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);

It works fine on Postman. It is neseccary on POST method because I need send some parameters. But how can I get/download pdf file in CycleJS from response. I have tried on frontend:

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'));
4

1 回答 1

3

这是一个使用RxJS的客户端 Cycle.js示例,从(模拟的)API 中获取值,然后单击按钮填充隐藏的表单,然后将表单提交给服务器脚本,该脚本返回一个 PDF 文档,该文档被定向到新的浏览器窗口或标签:

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')
});

这是一个使用xstream的客户端 Cycle.js示例:

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.jsxstream示例,使用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

于 2016-07-20T00:00:45.027 回答