• V
 

提供本地文件

问题

您想创建一个 HTTP 端点,响应 GET 请求并提供来自本地文件的内容,例如 PNG 图片。

解决方案

使用 File In 节点加载所需的内容,并将 Content-Type 设置为返回的文件类型的合适值。

示例

[{"id":"c7e341a0.381cc","type":"http in","z":"3045204d.cfbae","name":"","url":"/hello-file","method":"get","swaggerDoc":"","x":110,"y":720,"wires":[["2fb1c354.d04e3c"]]},{"id":"2fb1c354.d04e3c","type":"file in","z":"3045204d.cfbae","name":"","filename":"/tmp/node-red.png","format":"","x":290,"y":720,"wires":[["c9e28681.361d78"]]},{"id":"c9e28681.361d78","type":"change","z":"3045204d.cfbae","name":"设置头信息","rules":[{"t":"set","p":"headers","pt":"msg","to":"{}","tot":"json"},{"t":"set","p":"headers.content-type","pt":"msg","to":"image/png","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":470,"y":720,"wires":[["88974243.7768c"]]},{"id":"88974243.7768c","type":"http response","z":"3045204d.cfbae","name":"","x":610,"y":720,"wires":[]}]
[~]$ curl  http://localhost:1880/hello-file > file.png

讨论

在加载非文本文件(如图片)时,File In 节点必须被配置为返回 Buffer 对象。

为了让接收者知道如何处理文件,Content-Type 头必须设置为适当的 MIME 类型。上面的示例返回 .png 文件,将 Content-Type 头设置为 image/png