-1

below is my function to get file from my server writing in sailsJS. When i try run this function, my console throw me this type of error: TypeError: The header content contains invalid characters

In postman i send file in pdf format,

How content-type should look here?

fn: async function ({ id }, exits) {

    this.res.set('Content-disposition', `attachment; filename=${id}`, 'content-type', 'application/pdf')//here
    this.res.set('Access-Control-Allow-Origin', '*')

    const localPath = path.join(sails.config.custom.uploadDirectory, id)

    this.res.sendFile(localPath);
  }

and how to open fle in a browser instead of download him to desktop?

thanks in advance

2 Answers2

1

As per SailJS Documentation here, you can pass in a single object argument (headers) to set multiple header fields at once, where the keys are the header field names and the corresponding values are the desired values.

I think you are not setting header values in right way.

It should be sending the complete object if setting multiple values:

res.set({
  'Content-disposition': 'attachment',
  'content-type': 'application/pdf',
  'filename':  'filename.pdf'
})

[EDIT]: In order to open the File in Browser, You should add

Content-Disposition: `inline;filename="${id}"`
nircraft
  • 8,242
  • 5
  • 30
  • 46
  • 1
    As per [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) doc, Content-disposition header contains attachment as well as filename – Ayman Arif Apr 01 '20 at 13:28
  • okay, thanks, it works, but in my previous version my file had to be open in the browser instead of downloading it to the desktop, do you know how to do it? –  Apr 01 '20 at 13:44
  • to open it in browser I think you should add `Content-Disposition: inline;filename="myfile.pdf"` Check this answer here : https://stackoverflow.com/a/35913510/9386929 – nircraft Apr 01 '20 at 13:47
  • @AymanArif, You are right. But the filename is always optional. – nircraft Apr 01 '20 at 13:52
  • @nicraft can you update your post with function to open file in browser? –  Apr 01 '20 at 13:56
  • hmm.. looks like @AymanArif, already updated his answer and it got accepted. Can you please upvote mine at least? – nircraft Apr 01 '20 at 16:07
0

Try this:

fn: async function ({ id }, exits) {

res.set({
  'Content-disposition': `inline; filename="${id}"`,
  'content-type': 'application/pdf',
  'Access-Control-Allow-Origin': '*'
})

const localPath = path.join(sails.config.custom.uploadDirectory, id)
this.res.sendFile(localPath);
 }
Ayman Arif
  • 1,456
  • 3
  • 16
  • 40
  • okay, thanks, it works, but in my previous version my file had to be open in the browser instead of downloading it to the desktop, do you know how to do it? –  Apr 01 '20 at 13:43
  • Thanks to @nicraft I updated to inline. You can upvote his and my answer. – Ayman Arif Apr 01 '20 at 14:03