从云功能流式传输zip下载 [英] Streaming a zip download from cloud functions

查看:45
本文介绍了从云功能流式传输zip下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个firebase云功能,该功能使用express将图像的zip文件流传输到客户端.当我在本地测试云功能时,它可以正常工作.当我上传到Firebase时,出现此错误:

I have a firebase cloud function that uses express to streams a zip file of images to the client. When I test the cloud function locally it works fine. When I upload to firebase I get this error:

错误:发送标头后无法设置.

Error: Can't set headers after they are sent.

什么可能导致此错误?内存限制?

What could be causing this error? Memory limit?

export const zipFiles = async(name, params, response) => {


  const zip = archiver('zip', {zlib: { level: 9 }});


  const [files] = await storage.bucket(bucketName).getFiles({prefix:`${params.agent}/${params.id}/deliverables`});

  if(files.length){
    response.attachment(`${name}.zip`);
    response.setHeader('Content-Type', 'application/zip');
    response.setHeader('Access-Control-Allow-Origin', '*')

    zip.pipe(output);

    response.on('close', function() { 
      return output.send('OK').end(); // <--this is the line that fails
  });

  files.forEach((file, i) => {

    const reader = storage.bucket(bucketName).file(file.name).createReadStream();
    zip.append(reader, {name: `${name}-${i+1}.jpg`});

  });
  zip.finalize();
}else{
  output.status(404).send('Not Found'); 
}

推荐答案

弗兰克在评论中说的是正确的.开始发送任何内容正文之前,您需要确定所有标头,包括HTTP状态响应.

What Frank said in comments is true. You need to decide all your headers, including the HTTP status response, before you start sending any of the content body.

如果您想表达自己正在发送成功的响应,只需以与处理404错误相同的方式说出 output.status(200).事先做.当您传递响应时,您无需执行任何操作即可最终关闭响应.管道完成后,响应将自动刷新并完成.当您要纾困时,只应致电 end()很早就没有发送任何回复.

If you intend to express that you're sending a successful response, simply say output.status(200) in the same way that you did for your 404 error. Do that up front. When you're piping a response, you don't need to do anything to close the response in the end. When the pipe is done, the response will automatically be flushed and finalized. You're only supposed to call end() when you want to bail out early without sending a response at all.

请记住,Cloud Functions仅支持最大10MB的有效负载(了解有关限制的更多信息),因此,如果您尝试压缩的总数超过该总数,则将无法使用.实际上,根本没有流式"响应或分块响应.整个有效负载都内置在内存中,并作为一个单元传输出去.

Bear in mind that Cloud Functions only supports a maximum payload of 10MB (read more about limits), so if you're trying to zip up more than that total, it won't work. In fact, there is no "streaming" or chunked responses at all. The entire payload is being built in memory and transferred out as a unit.

这篇关于从云功能流式传输zip下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆