下载文件--代码
作者:互联网
var mongoose = require('mongoose'), fs = require('fs'), http = require('http'); //下载文件 exports.downloadFile = function(serverPath, downloadFileName, fileName, deleteFileName, socketId, returnHandle) { serverPath = serverPath.replace(/\\/g, "/"); //去掉http头 if (serverPath.indexOf('//') > -1) { serverPath = serverPath.split('//')[1]; } if (fileName == undefined || fileName == null || fileName.trim() == '') { fileName = downloadFileName; } var serverAddress = serverPath.substring(0, serverPath.indexOf('/')); //文件服务器IP及Port var serverApiPath = serverPath.substring(serverPath.indexOf('/'), serverPath.length); //文件服务器Api var serverHostName = serverAddress; //文件服务器地址 var serverPort = 80; //文件服务器端口 if (serverAddress.indexOf(':') > 0) { serverHostName = serverAddress.split(':')[0]; serverPort = parseInt(serverAddress.split(':')[1]); } var parameter = { FileName: fileName }; parameter = JSON.stringify(parameter); var options = { hostname: serverHostName, port: serverPort, path: serverApiPath, method: 'POST', headers: { "Content-Type": 'application/json', "Content-Length": parameter.length } }; var fileFullPath = BaseConst.FilePath + fileName; //创建写入流 var fileWriteStream = fs.createWriteStream(fileFullPath + '.temp'); var httpRequest = http.request(options, function(httpResponse) { httpResponse.on('data', function(data) { fileWriteStream.write(data); if (socketId != null && socketId != undefined && socketId.trim() != "") { socket.emitBySocketId(socketId, downloadFileName + "_DownloadSize", data.length); } }); httpResponse.on('end', function() { fileWriteStream.end(); if (deleteFileName != null && deleteFileName != undefined && deleteFileName.trim() != '') { //删除已有文件 exports.fileDeleteSync(BaseConst.FilePath + deleteFileName); } //重命名 exports.fileRenameSync(fileFullPath + '.temp', fileFullPath); if (socketId != null && socketId != undefined && socketId.trim() != "") { socket.emitBySocketId(socketId, downloadFileName + "_DownloadComplete", true); } returnHandle(null, { FileName: fileName }); }); }); httpRequest.write(parameter); httpRequest.on('error', function(err) { returnHandle(err); }); httpRequest.end(); };
标签:--,代码,socketId,fileName,下载,&&,var,serverAddress,serverPath 来源: https://www.cnblogs.com/aishuishuiADgai/p/15125383.html