programing

응답으로 Node.js 파일 전송

starjava 2023. 7. 26. 21:33
반응형

응답으로 Node.js 파일 전송

Expressjs 프레임워크는 다음을 포함합니다.sendfile()방법.전체 프레임워크를 사용하지 않고 어떻게 할 수 있습니까?

node-native-zip을 사용하여 보관 파일을 만들고 있는데 사용자에게 보내려고 합니다.

다음은 디스크에서 스트리밍하여 myfile.mp3를 보내는 프로그램의 예입니다(즉, 파일을 보내기 전에 전체 파일을 메모리로 읽지 않음).서버는 포트 2000을 수신합니다.

[업데이트] Aftershock이 댓글에 언급한 것처럼util.pump가 사라지고 스트림 프로토타입의 방법으로 대체되었습니다.pipe아래 코드는 이것을 반영합니다.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/ 에서 발췌

응답에서 파일(아카이브)을 보내려면 스트림을 사용해야 하며, 응답 헤더에서 적절한 내용 유형을 사용해야 합니다.

이 기능을 수행하는 예는 다음과 같습니다.

const fs = require('fs');

// Where fileName is name of the file and response is Node.js Reponse. 
responseFile = (fileName, response) => {
    const filePath = "/path/to/archive.rar"; // or any file format

    // Check if file specified by the filePath exists
    fs.exists(filePath, function (exists) {
        if (exists) {
            // Content-type is very interesting part that guarantee that
            // Web browser will handle response in an appropriate manner.
            response.writeHead(200, {
                "Content-Type": "application/octet-stream",
                "Content-Disposition": "attachment; filename=" + fileName
            });
            fs.createReadStream(filePath).pipe(response);
            return;
        }
        response.writeHead(400, { "Content-Type": "text/plain" });
        response.end("ERROR File does not exist");
    });
}

내용 유형 필드의 목적은 수신 사용자 에이전트가 적절한 에이전트 또는 메커니즘을 선택하여 사용자에게 데이터를 제공하거나 데이터를 적절한 방식으로 처리할 수 있을 정도로 본문에 포함된 데이터를 완전히 설명하는 것입니다.

"application/octet-stream"은 RFC 2046에서 "임의의 이진 데이터"로 정의되며, 이 컨텐츠 유형은 디스크에 저장하는 것이 목적입니다.

"download=[파일 이름]"은 다운로드할 파일의 이름을 지정합니다.

자세한 내용은 이 스택 오버플로 항목을 참조하십시오.

이게 도움이 됐어요.를 누르면 바로 파일 다운로드가 시작됩니다./your-route경로.

app.get("/your-route", (req, res) => {

         let filePath = path.join(__dirname, "youe-file.whatever");

         res.download(filePath);
}

네.download또한 빠른 방법입니다.

Bit Late but express는 삶을 더 편하게 만들기 위해 이것을 위한 도우미를 가지고 있습니다.

app.get('/download', function(req, res){
  const file = `${__dirname}/path/to/folder/myfile.mp3`;
  res.download(file); // Set disposition and send it.
});

Node.js native만 사용하여 fly 파일에 gzip 파일을 전송해야 하는 경우:

const fs = require('fs') // Node.js module
const zlib = require('zlib') // Node.js module as well

let sendGzip = (filePath, response) => {
    let headers = {
        'Connection': 'close', // intention
        'Content-Encoding': 'gzip',
        // add some headers like Content-Type, Cache-Control, Last-Modified, ETag, X-Powered-By
    }

    let file = fs.readFileSync(filePath) // sync is for readability
    let gzip = zlib.gzipSync(file) // is instance of Uint8Array
    headers['Content-Length'] = gzip.length // not the file's size!!!

    response.writeHead(200, headers)
    
    let chunkLimit = 16 * 1024 // some clients choke on huge responses
    let chunkCount = Math.ceil(gzip.length / chunkLimit)
    for (let i = 0; i < chunkCount; i++) {
        if (chunkCount > 1) {
            let chunk = gzip.slice(i * chunkLimit, (i + 1) * chunkLimit)
            response.write(chunk)
        } else {
            response.write(gzip)
        }
    }
    response.end()
}

언급URL : https://stackoverflow.com/questions/10046039/node-js-send-file-in-response

반응형