Skip to content

Send file as response #15453

Answered by jamesmosier
Corouna asked this question in Help
Jul 24, 2020 · 12 comments · 32 replies
Discussion options

You must be logged in to vote

Hi @Corouna. The res object is Node's built in response object, so if you wanted to send a file you could follow something like this example

    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);

Also be sure to access the file via process.cwd() as described here https://nextjs.org/docs/basic-features/data-fetching#reading-files-use-processcwd

Replies: 12 comments 32 replies

Comment options

You must be logged in to vote
3 replies
@kachkaev
Comment options

@gajendhir
Comment options

@eric-burel
Comment options

Answer selected by jamesmosier
Comment options

You must be logged in to vote
3 replies
@jamesmosier
Comment options

@cristiand391
Comment options

@Corouna
Comment options

Comment options

You must be logged in to vote
1 reply
@mfbx9da4
Comment options

Comment options

You must be logged in to vote
3 replies
@timneutkens
Comment options

@surjithctly
Comment options

@surjithctly
Comment options

Comment options

You must be logged in to vote
1 reply
@1finedev
Comment options

Comment options

You must be logged in to vote
3 replies
@m10rten
Comment options

@vasyl-zubach
Comment options

@m10rten
Comment options

Comment options

You must be logged in to vote
10 replies
@eric-burel
Comment options

@rohithandique
Comment options

@eric-burel
Comment options

@rohithandique
Comment options

@eric-burel
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
7 replies
@ghost
Comment options

@eric-burel
Comment options

@eric-burel
Comment options

@XenonyxBlaze
Comment options

@Lrios4403
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@andrewgreenh
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet