下载文件--代码

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

 

上一篇:Idea导入tomcat源码


下一篇:mongodb数据库的Java代码操作连接