【问题标题】:Is it possible to manually set the content-type header in reply.file()?是否可以在reply.file() 中手动设置内容类型标头?
【发布时间】:2015-02-23 04:27:48
【问题描述】:

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

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

无论我多么努力地说服它,hapijs 似乎只是一直在说“八位字节流”。我可以将我所有的文件存储在本地系统中并带有扩展名,但这并不是我真正想要做的。我宁愿使用正确的文件类型进行 hapi 回复。

【问题讨论】:

    标签: hapijs


    【解决方案1】:

    我认为这是 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】:

      似乎最简单的做法是不使用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'))
      

      【讨论】:

        【解决方案3】:

        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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-03-28
          • 2013-04-18
          • 1970-01-01
          • 2021-05-23
          • 2015-07-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多