pfooti
pfooti

Reputation: 2704

Is it possible to manually set the content-type header in reply.file()?

I have a file that I would like to serve from my local filesystem. That file, however, is not named according to naming conventions. Instead, I have stored some metadata elsewhere (in my database) about that particular file. What I'd like to do is say something like

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

It seems like hapijs just keeps saying 'octet stream' no matter how hard I try to convince it. I could store all my files in the local system with extensions, but that's not really what I want to do. I'd rather have hapi reply with the proper filetype.

Upvotes: 2

Views: 5269

Answers (3)

user4594602
user4594602

Reputation:

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

contentType can be one of following:

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;

Upvotes: 2

Gergo Erdosi
Gergo Erdosi

Reputation: 42063

I think this is a bug in hapi. The following should work:

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

I submitted a pull request to fix this issue (#1956). Will update this answer when the pull request gets accepted and released.

EDIT: The change was accepted, it will be in the 6.9.0 release.

EDIT 2: Hapi 6.9.0 has been released with this change in it.

Upvotes: 3

pfooti
pfooti

Reputation: 2704

Seems like the easiest thing to do is not use reply.file and instead just open the stream on my own and reply with it, thusly:

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

Upvotes: 3

Related Questions