我设法将文件从客户端大块上传到服务器,但是现在我想实现相反的方式。不幸的是,此部分缺少官方模块页面上的文档。
我要执行以下操作:
我不想使用简单的文件超链接的原因令人困惑:服务器上的文件已加密并重命名,因此我必须为每个下载请求解密并重命名它们。
有任何代码片段可以帮助我开始吗?
这是我正在使用的工作示例。但是以某种方式(也许仅以我为例),这可能会非常缓慢。
//== Server Side ss(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 Side /** Download a file from the object store * @param {string} name Name of the file to download * @param {string} originalFilename Overrules the file's originalFilename * @returns {$.Deferred} */ function 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); }; }());