使用socket.io-stream将文件从服务器流传输到客户端

使用socket.io-stream将文件从服务器流传输到客户端,第1张

使用socket.io-stream将文件从服务器流传输到客户端

这是我正在使用的工作示例。但是以某种方式(也许仅以我为例),这可能会非常缓慢。

//== Server Sidess(socket).on('filedownload', function (stream, name, callback) {    //== Do stuff to find your file    callback({        name : "filename",        size : 500    });    var MyFileStream = fs.createReadStream(name);    MyFileStream.pipe(stream);});//== Client Sidefunction downloadFile(name, originalFilename) {    var deferred = $.Deferred();    //== Create stream for file to be streamed to and buffer to save chunks    var stream = ss.createStream(),    fileBuffer = [],    fileLength = 0;    //== Emit/Request    ss(mysocket).emit('filedownload', stream, name, function (fileError, fileInfo) {        if (fileError) { deferred.reject(fileError);        } else { console.log(['File Found!', fileInfo]); //== Receive data stream.on('data', function (chunk) {     fileLength += chunk.length;     var progress = Math.floor((fileLength / fileInfo.size) * 100);     progress = Math.max(progress - 2, 1);     deferred.notify(progress);     fileBuffer.push(chunk); }); stream.on('end', function () {     var filedata = new Uint8Array(fileLength),     i = 0;     //== Loop to fill the final array     fileBuffer.forEach(function (buff) {         for (var j = 0; j < buff.length; j++) {  filedata[i] = buff[j];  i++;         }     });     deferred.notify(100);     //== Download file in browser     downloadFileFromBlob([filedata], originalFilename);     deferred.resolve(); });        }    });    //== Return    return deferred;}var downloadFileFromBlob = (function () {    var a = document.createElement("a");    document.body.appendChild(a);    a.style = "display: none";    return function (data, fileName) {        var blob = new Blob(data, {     type : "octet/stream" }),        url = window.URL.createObjectURL(blob);        a.href = url;        a.download = fileName;        a.click();        window.URL.revokeObjectURL(url);    };}());


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5016198.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存