res.sendFile 强制下载文件

Ash*_*y B 1 node.js express

我正在尝试发送要在浏览器中全屏显示的图像,但问题是以下代码强制将文件作为附件(已下载)发送,类似于res.download()而不是显示图像:

res.sendFile(file, {root: path.join(__dirname, '../storage')})
Run Code Online (Sandbox Code Playgroud)

有没有办法在不强制下载或不读取原始文件的情况下显示图像?

Ash*_*y B 6

我发现问题是该文件没有任何文件扩展名。由于res.sendFile()尝试自动设置内容类型标头,这导致了文件下载而不是显示的问题。

如果文件没有文件扩展名,您可以手动设置Content-Type标题,res.sendFiel()如下所示:

res.sendFile(file, {headers: {'Content-Type': 'image/jpeg'}})
Run Code Online (Sandbox Code Playgroud)

这将导致图像正确显示。