httpStream.js 1.2 KB

1234567891011121314151617181920212223242526272829303132
  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', (err) => {
  10. console.error(`Download stream error for file '${name}':`, err);
  11. http.response.statusCode = 404;
  12. http.response.end('not found');
  13. });
  14. if (cacheControl) {
  15. http.response.setHeader('Cache-Control', cacheControl);
  16. }
  17. http.response.setHeader('Content-Disposition', getContentDisposition(name, http?.params?.query?.download));
  18. };
  19. /** will initiate download, if links are called with ?download="true" queryparam */
  20. const getContentDisposition = (name, downloadFlag) => {
  21. const dispositionType = downloadFlag === 'true' ? 'attachment;' : 'inline;';
  22. const encodedName = encodeURIComponent(name);
  23. const dispositionName = `filename="${encodedName}"; filename=*UTF-8"${encodedName}";`;
  24. const dispositionEncoding = 'charset=utf-8';
  25. return `${dispositionType} ${dispositionName} ${dispositionEncoding}`;
  26. };