httpStream.js 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. export const httpStreamOutput = function(readStream, name, http, downloadFlag, cacheControl) {
  2. readStream.on('data', data => {
  3. http.response.write(data);
  4. });
  5. readStream.on('end', () => {
  6. // don't pass parameters to end() or it will be attached to the file's binary stream
  7. http.response.end();
  8. });
  9. readStream.on('error', () => {
  10. http.response.statusCode = 404;
  11. http.response.end('not found');
  12. });
  13. if (cacheControl) {
  14. http.response.setHeader('Cache-Control', cacheControl);
  15. }
  16. http.response.setHeader('Content-Disposition', getContentDisposition(name, http?.params?.query?.download));
  17. };
  18. /** will initiate download, if links are called with ?download="true" queryparam */
  19. const getContentDisposition = (name, downloadFlag) => {
  20. const dispositionType = downloadFlag === 'true' ? 'attachment;' : 'inline;';
  21. const encodedName = encodeURIComponent(name);
  22. const dispositionName = `filename="${encodedName}"; filename=*UTF-8"${encodedName}";`;
  23. const dispositionEncoding = 'charset=utf-8';
  24. return `${dispositionType} ${dispositionName} ${dispositionEncoding}`;
  25. };