【问题标题】:multipart/mixed response using NodeJS使用 NodeJS 的多部分/混合响应
【发布时间】:2015-09-02 13:37:11
【问题描述】:

我有以下场景:使用 NodeJS 返回一个包含以下项目的多部分/混合响应,我们控制通信的两端,因此我们应该能够消除互操作性问题。

  1. JSON 文件包含描述每个 ZIP 的节点列表,即 [{name: test1, desc: Test1 Desc, md5: 1234ABCD, file: zip-01.zip}, {name: test1, desc: Test1 Desc, md5: 1234ABCD, file: zip-02.zip}]
  2. ZIP 文件是从 mongo gridfs 存储中读取的
--whoop
Content-Disposition: attachment; name="zip"; filename="tobi.zip"
Content-Type: application/zip

... data here ...
--whoop
Content-Disposition: form-data; name="name"
Content-Type: text/plain

Tobi
--whoop--

我需要将此流式传输回用户,以便他们可以处理 JSON 文件,如果需要,展开他们感兴趣的特定 ZIP 文件。

通过查看 API 指南 http://expressjs.com/api.html 我不明白这怎么可能?我已正确返回单个 ZIP 文件,但需要支持此业务场景。

我正在尝试创建类似于以下内容的内容: HTTP multipart response using Perl or PHP

res 应该包含一个 JSON 文件和所有相关的 ZIP。

感谢任何帮助。谢谢。

J

【问题讨论】:

    标签: javascript json node.js multipartform-data


    【解决方案1】:

    解决方案看起来像这样 - 每个需要写入响应的项目​​调用。

                    res.writeHead(200, {
                        'Content-Type': 'multipart/x-mixed-replace; charset=UTF-8; boundary="' + SNAPSHOT_BOUNDARY + '"',
                        Connection: 'keep-alive',
                        Expires: 'Fri, 01 Jan 1990 00:00:00 GMT',
                        'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
                        Pragma: 'no-cache'
                    });
    
    feed.snapshots.forEach(function (item) {
                    writeResponse(item);
                });
    
        function writeResponse(item) {
            var buffer = new Buffer(0);
                var readStream = getGridFs().createReadStream({root: 'items', _id: snapshotItem._id});
    
                readStream.on('error', function (err) {
                    if (err) {
                        // handle error
                    }
                });
    
                readStream.on('data', function (chunk) {
                    buffer = Buffer.concat([buffer, chunk]);
                });
    
                readStream.on('end', function () {
                    res.write('\n\n' + SNAPSHOT_BOUNDARY + '\n');
                    res.write('Content-Disposition: filename="' + item.filename + '" \n');
                    res.write('Content-Type: application/zip \n');
                    res.write('Content-length: ' + buffer.length + '\n\n');
                    res.write(buffer);
                });
        }
    

    在超测试解析多部分响应时仍然存在问题 - 票在 https://github.com/felixge/node-formidable/issues/348 处打开

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-08
      • 2021-09-30
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多