【问题标题】:TypeError: The header content contains invalid charactersTypeError:标头内容包含无效字符
【发布时间】:2020-04-01 12:54:05
【问题描述】:

下面是我用sailsJS从我的服务器获取文件的函数。 当我尝试运行此函数时,我的控制台向我抛出了这种类型的错误: TypeError: The header content contains invalid characters

在邮递员中,我以 pdf 格式发送文件,

content-type 在这里应该是什么样子?

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);
  }

以及如何在浏览器中打开文件而不是下载到桌面?

提前致谢

【问题讨论】:

标签: javascript node.js


【解决方案1】:

根据 SailJS Documentation here,您可以传入单个对象参数(标头)来一次设置多个标头字段,其中keys 是标头字段名称和对应的@ 987654325@ 是所需的值。

我认为您没有以正确的方式设置标题值。

如果设置多个值,它应该发送完整的对象:

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

[编辑]:为了在浏览器中打开文件,你应该添加

Content-Disposition: `inline;filename="${id}"`

【讨论】:

  • 根据MDN doc,Content-disposition 标头包含附件和文件名
  • 好的,谢谢,它可以工作,但在我以前的版本中,我的文件必须在浏览器中打开,而不是下载到桌面,你知道怎么做吗?
  • 在浏览器中打开它我认为你应该添加Content-Disposition: inline;filename="myfile.pdf"在这里检查这个答案:stackoverflow.com/a/35913510/9386929
  • @AymanArif,你是对的。但文件名始终是可选的。
  • @nicraft 你能用在浏览器中打开文件的功能更新你的帖子吗?
【解决方案2】:

试试这个:

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);
 }

【讨论】:

  • 好的,谢谢,它可以工作,但在我以前的版本中,我的文件必须在浏览器中打开,而不是下载到桌面,你知道怎么做吗?
  • 感谢@nicraft 我更新为内联。你可以投票赞成他和我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
  • 2023-02-05
  • 2016-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多