是否可以在reply.file()中手动设置content-type标头?

时间:2014-09-17 22:07:50

标签: hapijs

我有一个文件,我想从我的本地文件系统提供服务。但是,该文件不是根据命名约定命名的。相反,我在其他地方(在我的数据库中)存储了一些关于该特定文件的元数据。我想做的就是说

reply.file(req.pre.item.actual_filename,
  {
    filename: req.pre.item.user_filename,
    mode: 'inline',
    'content-type': req.pre.item.mime_type
  });

看起来,无论我多么努力地说服它,所以hapijs一直在说'八重奏'。我可以将所有文件存储在带有扩展名的本地系统中,但这不是我想要做的。我宁愿用适当的文件类型进行hapi回复。

3 个答案:

答案 0 :(得分:3)

似乎最容易做的事情就是不使用reply.file,而只是自己打开流并回复它,因此:

serveItem: (req, reply)->
  out = fs.createReadStream path.resolve(tmpFolder, req.pre.item.get('real_filename'))
  reply(out).type(req.pre.item.get('mime_type'))

答案 1 :(得分:3)

我认为这是hapi中的一个错误。以下应该有效:

reply.file(req.pre.item.actual_filename,
{
  filename: req.pre.item.user_filename,
  mode: 'inline'
}).type(req.pre.item.mime_type);

我提交了拉取请求以解决此问题(#1956)。当拉取请求被接受并释放时,将更新此答案。

编辑:此更改已被接受,它将在6.9.0版本中发布。

编辑2: Hapi 6.9.0已经发布了此更改。

答案 2 :(得分:2)

reply(content).header('Content-Type', contentType).header("Content-Disposition", "attachment; filename=" + file);

contentType可以是以下之一:

case "pdf":
    contentType = 'application/pdf';
    break;
case "ppt":
    contentType = 'application/vnd.ms-powerpoint';
    break;
case "pptx":
    contentType = 'application/vnd.openxmlformats-officedocument.preplyentationml.preplyentation';
    break;
case "xls":
    contentType = 'application/vnd.ms-excel';
    break;
case "xlsx":
    contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    break;
case "doc":
    contentType = 'application/msword';
    break;
case "docx":
    contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    break;
case "csv":
    contentType = 'application/octet-stream';
    break;