简体   繁体   中英

How get file from POST request in CycleJS

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

Here's a client-side Cycle.js using RxJS example taking values from a (mocked) API, and upon button click populating a hidden form, then submitting the form to a server script that returns a PDF document which is directed to a new browser window or tab:

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

And here's a client-side Cycle.js using xstream example:

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

And for kicks here's a server-side Cycle.js and xstream example using Express receiving POST'ed data and returning a specified document:

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

To see these working together along with a page router check out cycle-isomorphic-file-download .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM