Serve up a file from disk.
    Two methods (chosen by ``settings.XSENDFILE``):
    (a) serve directly
    (b) serve by asking the web server to do so via the X-SendFile directive.
556305
def serve_file(path_to_file: str,
               offered_filename: str = None,
               content_type: str = None,
               as_attachment: bool = False,
               as_inline: bool = False) -> HttpResponseBase:
    
    # http://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files  # noqa
    # https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment  # noqa
    # https://djangosnippets.org/snippets/365/
    if offered_filename is None:
        offered_filename = os.path.basename(path_to_file) or ''
    if settings.XSENDFILE:
        response = HttpResponse()
        response['X-Sendfile'] = smart_str(path_to_file)
        content_length = os.path.getsize(path_to_file)
    else:
        response = FileResponse(open(path_to_file, mode='rb'))
        content_length = None
    add_http_headers_for_attachment(response,
                                    offered_filename=offered_filename,
                                    content_type=content_type,
                                    as_attachment=as_attachment,
                                    as_inline=as_inline,
                                    content_length=content_length)
    return response
614184
function tryServeWithBrotli(shouldTryGzip) {
      fs.stat(brotliFile, (err, stat) => {
        if (!err && stat.isFile()) {
          file = brotliFile;
          serve(stat);
        } else if (shouldTryGzip) {
          tryServeWithGzip();
        } else {
          statFile();
        }
      });
    }
609719
function(url, outFile, cb, persist, headers) {
    this.file.save(
      outFile,
      request.get(
        {
          url : url,
          headers : headers
        }
      ),
      persist,
      cb
    );
  }
446541
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath)
		throws IOException, ParseException {

		// make sure we request the "index.html" in case there is a directory request
		if (requestPath.endsWith("/")) {
			requestPath = requestPath + "index.html";
		}

		if (!requestPath.contains(".")) { // we assume that the path ends in either .html or .js
			requestPath = requestPath + ".json";
		}

		// convert to absolute path
		final File file = new File(rootPath, requestPath);

		if (!file.exists()) {
			// file does not exist. Try to load it with the classloader
			ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();

			try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
				boolean success = false;
				try {
					if (resourceStream != null) {
						URL root = cl.getResource("web");
						URL requested = cl.getResource("web" + requestPath);

						if (root != null && requested != null) {
							URI rootURI = new URI(root.getPath()).normalize();
							URI requestedURI = new URI(requested.getPath()).normalize();

							// Check that we don't load anything from outside of the
							// expected scope.
							if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
								LOG.debug("Loading missing file from classloader: {}", requestPath);
								// ensure that directory to file exists.
								file.getParentFile().mkdirs();
								Files.copy(resourceStream, file.toPath());

								success = true;
							}
						}
					}
				} catch (Throwable t) {
					LOG.error("error while responding", t);
				} finally {
					if (!success) {
						LOG.debug("Unable to load requested file {} from classloader", requestPath);
						HandlerUtils.sendErrorResponse(
							ctx,
							request,
							new ErrorResponseBody("File not found."),
							NOT_FOUND,
							Collections.emptyMap());
						return;
					}
				}
			}
		}

		if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		if (!file.getCanonicalFile().toPath().startsWith(rootPath.toPath())) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		// cache validation
		final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
		if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
			SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.HTTP_DATE_FORMAT, Locale.US);
			Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

			// Only compare up to the second because the datetime format we send to the client
			// does not have milliseconds
			long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
			long fileLastModifiedSeconds = file.lastModified() / 1000;
			if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
				}

				StaticFileServerHandler.sendNotModified(ctx);
				return;
			}
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
		}

		// Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
		final RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(file, "r");
		} catch (FileNotFoundException e) {
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("File not found."),
				NOT_FOUND,
				Collections.emptyMap());
			return;
		}

		try {
			long fileLength = raf.length();

			HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
			StaticFileServerHandler.setContentTypeHeader(response, file);

			// the job overview should be updated as soon as possible
			if (!requestPath.equals("/joboverview.json")) {
				StaticFileServerHandler.setDateAndCacheHeaders(response, file);
			}
			if (HttpHeaders.isKeepAlive(request)) {
				response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
			}
			HttpHeaders.setContentLength(response, fileLength);

			// write the initial line and the header.
			ctx.write(response);

			// write the content.
			ChannelFuture lastContentFuture;
			if (ctx.pipeline().get(SslHandler.class) == null) {
				ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
				lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
			} else {
				lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
					ctx.newProgressivePromise());
				// HttpChunkedInput will write the end marker (LastHttpContent) for us.
			}

			// close the connection, if no keep-alive is needed
			if (!HttpHeaders.isKeepAlive(request)) {
				lastContentFuture.addListener(ChannelFutureListener.CLOSE);
			}
		} catch (Exception e) {
			raf.close();
			LOG.error("Failed to serve file.", e);
			HandlerUtils.sendErrorResponse(
				ctx,
				request,
				new ErrorResponseBody("Internal server error."),
				INTERNAL_SERVER_ERROR,
				Collections.emptyMap());
		}
	}
459531
def _serve_file(self, path):
        
        request = self._py_object.request
        request.environ['PATH_INFO'] = '/%s' % path
        return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_response)
847969
public void service(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException
    {
	    boolean fileFound = sendResourceFile(req, resp);
		if (!fileFound)
		    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
//    	super.service(req, resp);
    }
289391
public Response serveFile( String uri, Properties header, File homeDir,
                               boolean allowDirectoryListing )
    {
        Response res = null;

        // Make sure we won't die of an exception later
        if ( !homeDir.isDirectory())
            res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT,
                    "INTERNAL ERRROR: serveFile(): given homeDir is not a directory." );

        if ( res == null )
        {
            // Remove URL arguments
            uri = uri.trim().replace( File.separatorChar, '/' );
            if ( uri.indexOf( '?' ) >= 0 )
                uri = uri.substring(0, uri.indexOf( '?' ));

            // Prohibit getting out of current directory
            if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 )
                res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
                        "FORBIDDEN: Won't serve ../ for security reasons." );
        }

        File f = new File( homeDir, uri );
        if ( res == null && !f.exists())
            res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT,
                    "Error 404, file not found." );

        // List the directory, if necessary
        if ( res == null && f.isDirectory())
        {
            // Browsers get confused without '/' after the
            // directory, send a redirect.
            if ( !uri.endsWith( "/" ))
            {
                uri += "/";
                res = new Response( HTTP_REDIRECT, MIME_HTML,
                        "<html><body>Redirected: <a href=\"" + uri + "\">" +
                                uri + "</a></body></html>");
                res.addHeader( "Location", uri );
            }

            if ( res == null )
            {
                // First try index.html and index.htm
                if ( new File( f, "index.html" ).exists())
                    f = new File( homeDir, uri + "/index.html" );
                else if ( new File( f, "index.htm" ).exists())
                    f = new File( homeDir, uri + "/index.htm" );
                    // No index file, list the directory if it is readable
                else if ( allowDirectoryListing && f.canRead() )
                {
                    String[] files = f.list();
                    String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

                    if ( uri.length() > 1 )
                    {
                        String u = uri.substring( 0, uri.length()-1 );
                        int slash = u.lastIndexOf( '/' );
                        if ( slash >= 0 && slash  < u.length())
                            msg += "<b><a href=\"" + uri.substring(0, slash+1) + "\">..</a></b><br/>";
                    }

                    if (files!=null)
                    {
                        for ( int i=0; i<files.length; ++i )
                        {
                            File curFile = new File( f, files[i] );
                            boolean dir = curFile.isDirectory();
                            if ( dir )
                            {
                                msg += "<b>";
                                files[i] += "/";
                            }

                            msg += "<a href=\"" + encodeUri( uri + files[i] ) + "\">" +
                                    files[i] + "</a>";

                            // Show file size
                            if ( curFile.isFile())
                            {
                                long len = curFile.length();
                                msg += " &nbsp;<font size=2>(";
                                if ( len < 1024 )
                                    msg += len + " bytes";
                                else if ( len < 1024 * 1024 )
                                    msg += len/1024 + "." + (len%1024/10%100) + " KB";
                                else
                                    msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB";

                                msg += ")</font>";
                            }
                            msg += "<br/>";
                            if ( dir ) msg += "</b>";
                        }
                    }
                    msg += "</body></html>";
                    res = new Response( HTTP_OK, MIME_HTML, msg );
                }
                else
                {
                    res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
                            "FORBIDDEN: No directory listing." );
                }
            }
        }

        try
        {
            if ( res == null )
            {
                // Get MIME type from file name extension, if possible
                String mime = null;
                int dot = f.getCanonicalPath().lastIndexOf( '.' );
                if ( dot >= 0 )
                    mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase());
                if ( mime == null )
                    mime = MIME_DEFAULT_BINARY;

                // Calculate etag
                String etag = Integer.toHexString((f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode());

                // Support (simple) skipping:
                long startFrom = 0;
                long endAt = -1;
                String range = header.getProperty( "range" );
                if ( range != null )
                {
                    if ( range.startsWith( "bytes=" ))
                    {
                        range = range.substring( "bytes=".length());
                        int minus = range.indexOf( '-' );
                        try {
                            if ( minus > 0 )
                            {
                                startFrom = Long.parseLong( range.substring( 0, minus ));
                                endAt = Long.parseLong( range.substring( minus+1 ));
                            }
                        }
                        catch ( NumberFormatException nfe ) {}
                    }
                }

                // Change return code and add Content-Range header when skipping is requested
                long fileLen = f.length();
                if (range != null && startFrom >= 0)
                {
                    if ( startFrom >= fileLen)
                    {
                        res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" );
                        res.addHeader( "Content-Range", "bytes 0-0/" + fileLen);
                        res.addHeader( "ETag", etag);
                    }
                    else
                    {
                        if ( endAt < 0 )
                            endAt = fileLen-1;
                        long newLen = endAt - startFrom + 1;
                        if ( newLen < 0 ) newLen = 0;

                        final long dataLen = newLen;
                        FileInputStream fis = new FileInputStream( f ) {
                            public int available() throws IOException { return (int)dataLen; }
                        };
                        fis.skip( startFrom );

                        res = new Response( HTTP_PARTIALCONTENT, mime, fis );
                        res.addHeader( "Content-Length", "" + dataLen);
                        res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                        res.addHeader( "ETag", etag);
                    }
                }
                else
                {
                    if (etag.equals(header.getProperty("if-none-match")))
                        res = new Response( HTTP_NOTMODIFIED, mime, "");
                    else
                    {
                        res = new Response( HTTP_OK, mime, new FileInputStream( f ));
                        res.addHeader( "Content-Length", "" + fileLen);
                        res.addHeader( "ETag", etag);
                    }
                }
            }
        }
        catch( IOException ioe )
        {
            res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." );
        }

        res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes
        return res;
    }
1196441
def sendTo(self, dest, chunkSize):
        
        vol = self.toVol
        paths = self.sink.getPaths(vol)

        if self.sink == dest:
            logger.info("Keep: %s", self)
            self.sink.keep(self)
        else:
            # Log, but don't skip yet, so we can log more detailed skipped actions later
            skipDryRun(logger, dest.dryrun, 'INFO')("Xfer: %s", self)

            receiveContext = dest.receive(self, paths)

            sendContext = self.sink.send(self)

            # try:
            #     receiveContext.metadata['btrfsVersion'] = self.btrfsVersion
            # except AttributeError:
            #     pass

            transfer(sendContext, receiveContext, chunkSize)

        if vol.hasInfo():
            infoContext = dest.receiveVolumeInfo(paths)

            if infoContext is None:
                # vol.writeInfo(sys.stdout)
                pass
            else:
                with infoContext as stream:
                    vol.writeInfo(stream)
180302
function onFile(__newFile, encoding, done) {
  var buffers = [];
  var options = this.options;

  // Check the file limit
  if (options.perMaxBytes && __newFile.byteCount > options.perMaxBytes) {
    return done(new Error('The file \'' + __newFile.filename + '\' beyond size limit, only accept less than ' + options.perMaxBytes + ' bytes'));
  }

  // Check the accept content type
  if (options.acceptTypes && options.acceptTypes.indexOf(__newFile.headers['content-type']) === -1) {
    return done(new Error('Content-type of the file \'' + __newFile.filename + '\' does not accepted'));
  }

  // Determine the file descriptor-- the unique identifier.
  // Often represents the location where file should be written.
  __newFile.fd;
  var uploadDir = __newFile.fd;
  if (uploadDir.substr(0, 1) !== '/') {
    uploadDir = '/' + uploadDir;
  }

  // When then 'data' event emited, push the chunk to the buffers array.
  __newFile.on('data', function (chunk) {
    buffers.push(chunk);
  });

  // When the 'end' event emited, upload the 'buffers' to the upyun server.
  __newFile.on('end', function () {
    var buffer = Buffer.concat(buffers);
    uploadToUpyun.bind({ options })(uploadDir, buffer, __newFile, done);
  });
}
526281
def send_video(path, refer, &callback)
      fail_back(&callback) if not File.exist?(path)
      @client.send_video(targetize, path, &callback)
    end
1366223
def handle(self, sock, read_data, path, headers):
        ""
        assert self.type is not None
        try:
            # Get the correct file
            try:
                fh = open(os.path.join(self.balancer.static_dir, "%s.http" % self.type))
            except IOError:
                fh = open(os.path.join(os.path.dirname(__file__), "static", "%s.http" % self.type))
            # Send it, using sendfile if poss. (no fileno() means we're probably using mock sockets)
            try:
                self._sendfile(sock.fileno(), fh.fileno(), 0, os.fstat(fh.fileno()).st_size)
            except (TypeError, AttributeError):
                sock.sendall(fh.read())
            # Close the file and socket
            fh.close()
            sock.close()
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise
1136632
public void putFile(File file, String path) throws IOException {
        OAuthRequest request = new OAuthRequest(Verb.POST, FILES_URL + encode(path));
        Multipart.attachFile(file, request);
        service.signRequest(accessToken, request);

        checkFiles(request.send());
    }
340811
function(name, file) {
    if (!ternLoaded[name]) {
      $.ajax({
        url: file,
        dataType: 'script',
        success: function(data) {
          ternServer.server.addFile(name, data);
          ternLoaded[name] = true;
        }
      });
    }
  }
1363631
public function serve()
	{
		return self::serve_file($this->_filename, $this->_saveas, $this->_disposition, $this->_acceptranges);
	}
913135
def wrapped_sendfile(act, offset, length):
    
    if sendfile:
        offset, sent = sendfile.sendfile(
            act.sock.fileno(),
            act.file_handle.fileno(),
            offset, length
        )
    else:
        act.file_handle.seek(offset)
        sent = act.sock._fd.send(act.file_handle.read(length))
    return sent
1154938
function serve(res, file, maxAge) {
  log.debug(`Serving: ${ file }`)
  res.status(200)
    .set('Cache-Control', `max-age=${ maxAge }`)
    .sendFile(file, err => {
      if (err) {
        log.error(err)
        res.status(err.status).end()
        return
      }
    })
}
760568
def putbinaryfile(localfile, remotefile = File.basename(localfile),
		      blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      if @resume
        begin
          rest_offset = size(remotefile)
        rescue Net::FTPPermError
          rest_offset = nil
        end
      else
	rest_offset = nil
      end
      f = open(localfile)
      begin
	f.binmode
	storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block)
      ensure
	f.close
      end
    end