在节点中使用sftp下载音频文件

时间:2018-01-02 20:17:37

标签: javascript node.js audio sftp

我要做的是点击链接,当我这样做时,它会连接到我的服务器并下载浏览器提供的音频文件。我能够连接到我的服务器并下载.wav文件。但是当我尝试用Windows媒体播放器打开音频文件时,我收到一个错误:

Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.

app.get('/download', (req, res) => {

    var config = {
        host: 'someHost',
        port: '22',
        username: 'user',
        password: 'root'            
    }
    var fileName = "hello.wav"; //File Name
    // Connect to server
    sftp.connect(config).then(() => {  
        // Get the file as a readable stream
        sftp.get(fileName).then((data) => {
            res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
            // Set headers to download file 
            res.setHeader('Content-Type', 'application/audio/wav');
            // pipe stream 
            data.pipe(res);
        });
    });
});

文件在存储到服务器之前可播放,或者在由WinSCP等外部应用程序下载时可播放。但是我不确定通过ssh2-sftp-client模块下载时CODEC会发生什么。

解决方案

我发现编码类型存在一些问题。在ssh2-sftp-client模块内部指定可以更改sftp.get(remoteFilePath, [useCompression], [encoding]);的压缩和编码类型。所以我将压缩更改为false,因为它默认为true,编码值为null,因为它默认为utf8

app.get('/download', (req, res) => {

    var config = {
        host: 'someHost',
        port: '22',
        username: 'user',
        password: 'root'            
    }
    var fileName = "hello.wav"; //File Name
    // Connect to server
    sftp.connect(config).then(() => {  
        // Get the file as a readable stream
        sftp.get(fileName, "false", null).then((data) => {
            res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
            // Set headers to download file 
            res.setHeader('Content-Type', 'application/audio/wav');
            // pipe stream 
            data.pipe(res);
        });
    });
});

0 个答案:

没有答案