node/express Force browser to download file with custom name

前端 未结 2 1430
旧时难觅i
旧时难觅i 2021-01-19 04:22

I\'ve built a node/express website for my university project that, after searching for an ID of a law, it shows a big table with all files in different formats and languages

相关标签:
2条回答
  • 2021-01-19 04:47

    In Express 4 and later, there are 2 helper functions to change the content-type and specify attachment disposition:

    res.type("application/octet-stream");
    res.attachment("filename.ext");
    

    See docs for type and attachment.

    0 讨论(0)
  • 2021-01-19 05:04

    You need to add a new header to the response object to indicate the file name and do a regular download.

    res.set("Content-Disposition", "attachment;filename=somefile.ext");
    

    You could also use "inline" if instead you want the browser to try to open the file within it self, like with Chrome does with pdf files.

    res.set("Content-Disposition", "inline;filename=somefile.ext");
    

    As per @Thomas suggestion, also is a good idea to include always the right content type:

    res.set("Content-Type", "application/octet-stream");
    
    0 讨论(0)
提交回复
热议问题