Rails从二进制数据流

时间:2018-05-03 14:23:16

标签: ruby-on-rails node.js zip binaryfiles

我有一个数据API来接收来自文件系统的数据。 data-API是nodeJS服务器。我们的网络服务器是一个Rails服务器。从Web服务器,我将参数发送到我想要下载的文件的API。然后,data-API会压缩请求文件并将zip作为二进制数据发回。

到目前为止一切正常。现在来到我被困的地方。我想将二进制数据作为下载提供给浏览器。我可以将二进制数据转换为zip文件并将其发送到浏览器,或者使用另一个聪明的解决方案,将二进制数据作为下载提供。

这是我到目前为止所做的事情

Rails网络服务器端:

app/controllers/simulation_controller.rb

def download_multiple
  files = JSON.parse(params[:files])
  file_list = @simulation.sweep_points.find(params[:sweep_point_id]).file_list
  send_data file_list.zip(files: files), filename: 'archive.zip', type: 'application/zip', disposition: 'attachment'
end

app/models/file_list.rb

def zip
  uuid = SecureRandom.uuid
  simulation = sweep_point.simulation
  files = files[:files].join(" ")
  url = URI.parse("http://localhost:3003/files/zip/#{simulation.name}/#{uuid}");
  req = Net::HTTP::Get.new(url.to_s)
  req.add_field("files", files)
  res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
  content = res.body
  content.force_encoding("ASCII-8BIT")
end

nodeJS data-API方面:

exports.zip_simulation_files = (req, res) => {
  const { headers, method, url } = req;
  var simulation = req.params.simulation;
  var uuid = req.params.uuid;
  var files, command;

  req.on("error", (err) => {
    console.error(err);
  });

  files = req.headers.files;
  command = "cd postprocess/bumblebee-zip " +  "run" + simulation + " " + uuid + " " + "'" + files + "'";

  execute(command, (data) => {
    res.on("error", (err) => {
      console.error(err);
    });

    const zipFilePath = "/home/samuel/test_bumblebee/.zips/run" + simulation + "-files-" + uuid + ".zip"

    var zipFile = fs.readFileSync(zipFilePath);
    var stats = fs.statSync(zipFilePath);
    res.writeHead(200, {
      'Content-Type': 'application/zip',
      'Content-Disposition': 'attachment; filename="archive.zip"',
      'Content-Length': stats.size,
      'Content-Transfer-Encoding': 'binary'
    });
    res.end(zipFile, 'binary');
  });
}

到目前为止,我收到的回复是一个字符串,似乎是一个二进制字符串。以此开始和结束:

  

" PK \ X03 \ X04 \ X14 \ X00 \ X00 \ X00 \ B \ X00 \ xA8 \ X89 \ xDBJ \ XB1 \ XB8 \ XA1 \ xBF2 \ X03 \ X00 \ X00 \ xB7F \ X00 \ X006 \ x00 \ x1C \ x00runZhangD3FINAL / 13.0V / annihilation_abs_profile_001.outUT \ t \ x00 \ x0 ....... x06 \ x00 \ x00 \ x00 \ x00 \ x05 \ x00 \ x05 \ x00l \ x02 \ x00 \ x00) \ X10 \ X00 \ X00 \ X00 \ X00"

我试图将二进制数据字符串转换为zip文件或将流直接呈现给浏览器,但没有任何效果,我研究了不同的解决方案。没有创建zip或者二进制文件不被视为正确的数据。

什么是好的解决方案?

0 个答案:

没有答案
相关问题