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

时间:2016-07-18 13:49:59

标签: javascript rxjs 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方法的必要条件,因为我需要发送一些参数。但是如何从响应中获取/下载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'));

1 个答案:

答案 0 :(得分:3)

这是一个客户端 Cycle.js,使用RxJS示例从(模拟的)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')
});

以下是使用Cycle.js示例的客户端 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.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