Как отправить почтовый файл на сервер nodejs с помощью express сервера - PullRequest
0 голосов
/ 21 апреля 2020

Я создаю приложение, в котором требуется сохранить данные в отдельные и сжать эти файлы в zip-файл. эти файлы находятся на заднем конце, и я не мог отправить этот созданный внутренний конец zip-файл на передний конец, который реагирует в этом случае

express js код

app.post("/download",function(request,response,next){
    let sheets=request.body["sheets"];
    let charts=request.body["charts"];
    let compressedSheets=LZString.compress(JSON.stringify(sheets));

    fs.writeFile(__dirname+'/public/dataModel.txt', compressedSheets, function (err) {
        if (err) throw err;
        console.log('Replaced!');

      },()=>{
        fs.writeFile(__dirname+'/public/Report.json',charts,function(err){
            if(err){
                console.log(err);
            }
        },()=>{
            var archiver = require('archiver');
            var output = fs.createWriteStream(__dirname+'/public/example.zip');
            var archive = archiver('zip', {
                gzip: true,
                zlib: { level: 9 } // Sets the compression level.
            });

            archive.on('error', function(err) {
            throw err;
            });
            archive.pipe(output);
            archive.file(__dirname+'/public/dataModel.txt', {name: 'dataModel.txt'});
            archive.file(__dirname+'/public/Report.json', {name: 'Report.json'});


            archive.finalize().then(()=>{
                response.setHeader('Content-disposition', 'attachment; filename=example.zip');
                response.download(__dirname+'/public/example.zip');
            });

        })
      });

реагировать код

handleSaveAs=function(){


    let data=new FormData();
    data.append('sheets',JSON.stringify(this.state.sheets));
    data.append('charts',JSON.stringify(this.state.charts));


    axios
    .post("http://localhost:4001/download",data)
    .then(res=>{
      console.log(res);
      const element = document.createElement("a");
      const file = new Blob([res.data], {type: 'application/zip'});
      element.href = URL.createObjectURL(file);
      element.download = "untitled.zip";
      document.body.appendChild(element);
      element.click();
    })

при условии, что все операции импорта обрабатываются правильно, а zip-файл создается правильно на серверной части. проблема только с отправкой этого на передний конец

любая помощь будет оценена спасибо

1 Ответ

0 голосов
/ 21 апреля 2020

Вы можете использовать встроенные fs из Node.js для потоковой передачи данных во внешний интерфейс.

//Filestream middleware that takes in the file path as the parameter

const streamW = (pathToZip) => {
 return (req, res, next) => {

//Create a readable stream
const readableStream = fs.createReadStream(pathToZip, 'the_encoding_here');

//Pipe it into the HTTP response
readableStream.pipe(res)

  next();

}};

//The route that you want to hit using the front-end to get the file
//Call the middleware and pass in the path to the zip
router.get('/downloadRoute', streamW('path_to_zip'), (req, res) => {

     //Send the data to the front end by calling res
     res

// });
...