Download the file of unkown type from the given location by saving it
automatically to disk

@param {MozMillController} controller
MozMillController of the browser window
@param {string} url
URL of the file which has to be downloaded
967300
function(controller, url) {
  controller.open(url);

  // Wait until the unknown content type dialog has been opened
  controller.waitForEval("subject.getMostRecentWindow('').document.documentElement.id == 'unknownContentType'",
                         gTimeout, 100, mozmill.wm);

  utils.handleWindow("type", "", function (controller) {
    // Select to save the file directly
    var saveFile = new elementslib.ID(controller.window.document, "save");
    controller.waitThenClick(saveFile, gTimeout);
    controller.waitForEval("subject.selected == true", gTimeout, 100,
                           saveFile.getNode());
  
    // Wait until the OK button has been enabled and click on it
    var button = new elementslib.Lookup(controller.window.document,
                                        '/id("unknownContentType")/anon({"anonid":"buttons"})/{"dlgtype":"accept"}');
    controller.waitForElement(button, gTimeout);
    controller.waitForEval("subject.okButton.hasAttribute('disabled') == false", gTimeout, 100,
                           {okButton: button.getNode()});
    controller.click(button);
  });
}
709703
function download(downloadUrl, filename, callback, ondata) {
    var url = require("url").parse(downloadUrl);
    var out = require("fs").createWriteStream(filename, { flags: 'w', encoding: null, mode: 0666 });
    var bytes = 0, total = -1;
    var options = {
        "hostname" : url["host"],
        "method" : "GET",
        "path" : url["path"],
        "agent" : false
    }

    // Reconfigure request options if an HTTP proxy setting exists
    if (process.env.http_proxy) {
        var http_proxy = require("url").parse(process.env.http_proxy);
        options["hostname"] = http_proxy["hostname"];
        options["port"] = http_proxy["port"];
        options["path"] = url["href"];
        options["headers"] = {
            "Host" : url["host"]
        };
    }

    var req = require(path.join(__dirname, "..", "lib", "follow-redirects.js")).http.request(options,
                                                                                             function(res) {
        if (res.headers["content-length"]) {
            total = parseInt(res.headers["content-length"], 10);
        }
        if (res.statusCode != 200) {
            res.setEncoding(null);
            callback(new Error("Download failed: HTTP status code "+res.statusCode), -1);
            return;
        }
        res.on("data", function(chunk) {
            bytes += chunk.length;
            if (ondata) ondata(chunk.length, total);
            out.write(chunk);
        });

        res.on("end", function() {
            callback(null, bytes);
        });
    });
    req.on("error", function(e) {
        callback(e, -1);
    });
    req.end();
}
539117
function updateDownloadLink( anchor, objectUrl, fileName ) {
    if ( window.updateDownloadLinkIe11 ) {
        return window.updateDownloadLinkIe11( ...arguments );
    }
    anchor.setAttribute( 'href', objectUrl || '' );
    anchor.setAttribute( 'download', fileName || '' );
}
643470
public String downloadFileFromServer(String url, String fileName, String targetFileDir) throws Exception {

        // 下载的路径
        String localDir = getLocalDownloadDirPath();

        // 设置远程地址
        RemoteUrl remoteUrl = new RemoteUrl(url, hostList);

        // 下载
        return restfulMgr
                .downloadFromServer(remoteUrl, fileName, localDir, localDownloadDirTemp, targetFileDir,
                        enableLocalDownloadDirInClassPath,
                        retryTime,
                        retrySleepSeconds);

    }
511613
def finalize_download(url, download_to_file, content_type, request):
    
    # If format is given, a format check is performed.
    if content_type and content_type not in request.headers['content-type']:
        msg = 'The downloaded file is not of the desired format'
        raise InvenioFileDownloadError(msg)

    # Save the downloaded file to desired or generated location.
    to_file = open(download_to_file, 'w')
    try:
        try:
            while True:
                block = request.read(CFG_FILEUTILS_BLOCK_SIZE)
                if not block:
                    break
                to_file.write(block)
        except Exception as e:
            msg = "Error when downloading %s into %s: %s" % \
                  (url, download_to_file, e)
            raise InvenioFileDownloadError(msg)
    finally:
        to_file.close()

    # Check Size
    filesize = os.path.getsize(download_to_file)
    if filesize == 0:
        raise InvenioFileDownloadError("%s seems to be empty" % (url,))

    # download successful, return the new path
    return download_to_file
201
public function submit($controller)
    {
        set_time_limit(0);

        // Download method calls exit() so clean session here
        $this->session->delete('file_manager_selected');

        $destination = $this->file->getTempFile();
        $files = $controller->getSubmitted('files');

        /* @var $file \SplFileInfo */
        $file = reset($files);

        $path = $file->getRealPath();
        $filename = $file->getBasename();

        if ($file->isFile()) {
            $result = $this->zip->file($path, $destination);
        } else if ($file->isDir()) {
            $result = $this->zip->directory($path, $destination, $filename);
        }

        if (!empty($result)) {
            $controller->download($destination, "$filename.zip");
        }
    }
965739
function getDownloadlink(map,title){
	var url = decodeURIComponent(map.url),
		sig = (map.s || map.sig)? '&signature='+(map.s || map.sig) : '',
		tit = '&title='+title;
	return url+sig+tit;
}
639413
def _download_from_url(self, url):
        
        ext = get_file_extension(url)
        if "?" in url:
            ext = get_file_extension(os.path.splitext(url.split("?")[0]))
        filepath = "/tmp/%s.%s" % (uuid.uuid4().hex, ext)
        request.urlretrieve(url, filepath)
        return filepath
121883
function downloader(url, saveAtPath, callback) {
  // Handle the parameter errors
  if (!url || !saveAtPath) {
    return callback(new Error("You need to provide the URL and the location to save the file!"));
  }
  if (url && typeof url !== "string") {
    return callback(new Error("The parameter 'url' must be a string"));
  }
  if (saveAtPath && typeof saveAtPath !== "string") {
    return callback(new Error("The parameter 'saveAtPath' must be a string"));
  }
  if (callback && typeof callback !== "function") {
    throw new Error("The callback provided must be a function");
  }

  var httpClient = url.indexOf("https://") === 0 ? https : http;

  // The directory to save the file.
  var dirToSave = path.dirname(saveAtPath);

  // Verify if the directory to save exists before downloading.
  fs.stat(dirToSave, function gettingStats(err) {
    if (err) {
      return callback(new Error("The path '" + dirToSave + "' does NOT exist!"));
    }

    var req = httpClient.get(url, function requestHandler(res) {
      if (res.statusCode === 404) {
        return callback(new Error("The resource at the given URL " + url + " does NOT exist"));
      }

      var chunks = [];

      res.on("data", function(chunk) {
        chunks.push(chunk);
      });

      res.on("end", function() {
        var buffer = Buffer.concat(chunks);

        // Finished downloading and getting the buffer to be saved.
        fs.writeFile(saveAtPath, buffer, function(err) {
          if (err) {
            var error = new Error("Error while saving image: " + err.message);
            if (err.code === "EISDIR") {
              error = new Error("Cannot save the url " + url + " as a directory " + saveAtPath);
            }
            callback(error);
          }

          fs.stat(saveAtPath, function(err, stat) {
            if (err) {
              callback(new Error("Error while getting image stats: " + err.message));
            }

            // Creating the response object.
            var response = {
              downloaded: true,
              filePath: saveAtPath,
              size: stat.size
            };

            // The request to the URL was successful and the file was saved.
            callback(null, response);
          });
        });
      });

    });

    // Handle errors during the request.
    req.on("error", function(error) {
      if (error) {
        if (error.code === "ENOTFOUND") {
          return callback(new Error("There's no internet connectivity to " + url));

        } else {
          var unknownError = new Error("Unknown error to save " + url + " as " + saveAtPath);
          unknownError.stack = error.stack;
          return callback(unknownError);
        }
      }
    });
  });
}
76168
function toDataUrl(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    };
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}
518259
@GetMapping("/setting/download/api/json")
    public void downloadApiJson(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) {
        this.validationSessionComponent.sessionCheck(req);
        url = new String(Base64.getDecoder().decode(url));
        List<ValidationData> list = this.msgSettingService.getValidationData(method, url);
        ValidationFileUtil.sendFileToHttpServiceResponse(method + url.replaceAll("/", "-") + ".json", list, res);
    }
506789
function( absUrl, triggerData, settings, deferred ) {
            var fileUrl = this._createFileUrl( absUrl );

            return $.proxy(function( html, textStatus, xhr ) {
                //pre-parse html to check for a data-url,
                //use it as the new fileUrl, base path, etc
                var content,

                    // TODO handle dialogs again
                    pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + this._getNs() + "role=[\"']?page[\"']?[^>]*>)" ),

                    dataUrlRegex = new RegExp( "\\bdata-" + this._getNs() + "url=[\"']?([^\"'>]*)[\"']?" );

                // data-url must be provided for the base tag so resource requests
                // can be directed to the correct url. loading into a temprorary
                // element makes these requests immediately
                if ( pageElemRegex.test( html ) &&
                    RegExp.$1 &&
                    dataUrlRegex.test( RegExp.$1 ) &&
                    RegExp.$1 ) {
                    fileUrl = $.mobile.path.getFilePath( $("<div>" + RegExp.$1 + "</div>").text() );

                    // We specify that, if a data-url attribute is given on the page div, its value
                    // must be given non-URL-encoded. However, in this part of the code, fileUrl is
                    // assumed to be URL-encoded, so we URL-encode the retrieved value here
                    fileUrl = this.window[ 0 ].encodeURIComponent( fileUrl );
                }

                //dont update the base tag if we are prefetching
                if ( settings.prefetch === undefined ) {
                    this._getBase().set( fileUrl );
                }

                content = this._parse( html, fileUrl );

                this._setLoadedTitle( content, html );

                // Add the content reference and xhr to our triggerData.
                triggerData.xhr = xhr;
                triggerData.textStatus = textStatus;

                // DEPRECATED
                triggerData.page = content;

                triggerData.content = content;

                triggerData.toPage = content;

                // If the default behavior is prevented, stop here!
                // Note that it is the responsibility of the listener/handler
                // that called preventDefault(), to resolve/reject the
                // deferred object within the triggerData.
                if ( this._triggerWithDeprecated( "load", triggerData ).event.isDefaultPrevented() ) {
                    return;
                }

                // rewrite src and href attrs to use a base url if the base tag won't work
                if ( this._isRewritableBaseTag() && content ) {
                    this._getBase().rewrite( fileUrl, content );
                }

                this._include( content, settings );

                // Remove loading message.
                if ( settings.showLoadMsg ) {
                    this._hideLoading();
                }

                deferred.resolve( absUrl, settings, content );
            }, this);
        }
1224361
function saveUrlToFile(url, filePath) {
  return new Promise((resolve, reject) => {
    const outFile = fs.createWriteStream(filePath);
    const protocol = url.startsWith('https') ? https : http;
    protocol.get(url, (response) => {
      response.pipe(outFile);
      response.on('end', () => resolve(filePath));
      response.on('error', (err) => {
        // outFile.destroy();
        // fs.unlinkSync(filePath);
        reject(err);
      });
    })
      .on('error', (err) => {
        reject(err);
      });
  });
}
904345
def download(url, *args, max_size: nil, content_length_proc: nil, progress_proc: nil, destination: nil, **options)
      io = open(url, *args, **options, rewindable: false)

      content_length_proc.call(io.size) if content_length_proc && io.size

      if max_size && io.size && io.size > max_size
        raise Down::TooLarge, "file is too large (max is #{max_size/1024/1024}MB)"
      end

      extname  = File.extname(URI(url).path)
      tempfile = Tempfile.new(["down-wget", extname], binmode: true)

      until io.eof?
        chunk = io.readpartial(nil, buffer ||= String.new)

        tempfile.write(chunk)

        progress_proc.call(tempfile.size) if progress_proc

        if max_size && tempfile.size > max_size
          raise Down::TooLarge, "file is too large (max is #{max_size/1024/1024}MB)"
        end
      end

      tempfile.open # flush written content

      tempfile.extend Down::Wget::DownloadedFile
      tempfile.url     = url
      tempfile.headers = io.data[:headers]

      download_result(tempfile, destination)
    rescue
      tempfile.close! if tempfile
      raise
    ensure
      io.close if io
    end
1293525
function downloadFile(cb) {
      if(task.file_path) {
        // Download the file
        var stream = fs.createWriteStream(path);

        // Store error if statusCode !== 200
        var err;
        stream.on("finish", function() {
          cb(err);
        });

        var urlToDownload = url.parse(task.file_path, false, true);

        // deny queries to ElasticSearch and other vulnerable services
        if(task.config.forbiddenPorts && task.config.forbiddenPorts.indexOf(urlToDownload.port) !== -1) {
          stream.end();
          return fs.unlink(path, function() {
            cb(new Error('Trying to access forbidden port: ' + urlToDownload.port));
          });
        }

        var req = request(urlToDownload.protocol + "//" + urlToDownload.host)
          .get(urlToDownload.path);

        // Warning, Black magic.
        // Streaming and checking for status code is no easy task...
        // Hours spent optimizing: 22
        req.end(function() {}).req.once('response', function(res) {
          if(res.statusCode !== 200) {
            if(res.statusCode === 410) {
              err = new Error('410 Gone');
              err.skip = true;
            }
            else {
              err = new Error('Error downloading file, got status ' + res.statusCode);
            }

            stream.end();
            this.abort();
          }
        });
        req.pipe(stream);
      }
      else {
        cb(null);
      }
    }
585758
function download(input, output) {
	if (!output) output = input.split("/").pop();
	var file = fs.createWriteStream(output);
	var request = http.get(input, response => { response.pipe(file); });
}
684466
def http_post_download(url, data, dest)
    File.open(dest, "w") do |io|
      req = HTTPI::Request.new(:url => url, :body => data)
      req.on_body { |d| io << d; d.length }
      HTTPI.post(req)
    end
    true
  end