Node.js readFileSync ZIP file

前端 未结 3 1847
甜味超标
甜味超标 2021-01-20 13:46

I am trying to read a ZIP file and output it to the browser, get the code that\'s shown on the page and save it as a ZIP file

fs.readFileSync(\'/dir/file.zip         


        
3条回答
  •  半阙折子戏
    2021-01-20 14:15

    ZIP is a binary file type, when you output it in a browser as a text and copy-paste the text to a text editor, you won't get the same value as in the original file (likely web browser will interpret some of its contents as HTML tags, and/or a copy-paste will mangle some binary characters, and/or a text editor itself will mangle them).

    What you should do is set appropriate HTTP response headers when serving the file to the browser, so that the browser knows it's a ZIP and can display the user a file download prompt. If you don't send any response headers, browser will just display contents as a text file which doesn't make sense.

    Have a look at this question which has a PHP solution:

    https://stackoverflow.com/a/10817739/245966

    Basically you need to set appropriate Content-Type and Content-Disposition header, and (optionally) Content-Length.

    setResponseHeader('Content-Disposition: attachment; filename=myfile.zip');
    setResponseHeader('Content-Type: application/zip');
    setResponseHeader('Content-Length: ' + fileLengthInBytes);
    

    Replace setResponseHeader with appropriate call to your HTTP framework which sets the response header.

提交回复
热议问题