Vapor Documentation Beta

Structure File​IO

public struct FileIO

FileIO is a convenience wrapper around SwiftNIO's NonBlockingFileIO.

It can read files, both in their entirety and chunked.

let fileio = try c.make(FileIO.self)

fileio.readFile(at: "/path/to/file.txt") { chunk in
    print(chunk) // part of file
}

fileio.collectFile(at: "/path/to/file.txt").map { file in
    print(file) // entire file
}

It can also create streaming HTTP responses.

let fileio = try c.make(FileIO.self)
router.get("file-stream") { req -> Response in
    return fileio.streamFile(at: "/path/to/file.txt", for: req)
}

Streaming file responses respect E-Tag headers present in the request.

Methods

collect​File(at:​)

public func collectFile(at path: String) -> EventLoopFuture<ByteBuffer>

Reads the contents of a file at the supplied path.

let data = try req.fileio().read(file: "/path/to/file.txt").wait()
print(data) // file data

Parameters

path String

Path to file on the disk.

Returns

Future containing the file data.

read​File(at:​chunk​Size:​on​Read:​)

public func readFile(at path: String, chunkSize: Int = NonBlockingFileIO.defaultChunkSize, onRead: @escaping (ByteBuffer) -> EventLoopFuture<Void>) -> EventLoopFuture<Void>

Reads the contents of a file at the supplied path in chunks.

try req.fileio().readChunked(file: "/path/to/file.txt") { chunk in
    print("chunk: \(data)")
}.wait()

Parameters

path String

Path to file on the disk.

chunk​Size Int

Maximum size for the file data chunks.

on​Read @escaping (Byte​Buffer) -> Event​Loop​Future<Void>

Closure to be called sequentially for each file data chunk.

Returns

Future that will complete when the file read is finished.

stream​File(at:​chunk​Size:​)

public func streamFile(at path: String, chunkSize: Int = NonBlockingFileIO.defaultChunkSize) -> Response

Generates a chunked HTTPResponse for the specified file. This method respects values in the "ETag" header and is capable of responding 304 Not Modified if the file in question has not been modified since last served. This method will also set the "Content-Type" header automatically if an appropriate MediaType can be found for the file's suffix.

router.get("file-stream") { req -> HTTPResponse in
    return try req.fileio().chunkedResponse(file: "/path/to/file.txt")
}

Parameters

path String

Path to file on the disk.

req

HTTPRequest to parse "If-None-Match" header from.

chunk​Size Int

Maximum size for the file data chunks.

Returns

A 200 OK response containing the file stream and appropriate headers.

write​File(_:​at:​)

public func writeFile(_ buffer: ByteBuffer, at path: String) -> EventLoopFuture<Void>

Write the contents of buffer to a file at the supplied path.

let data = ByteBuffer(string: "ByteBuffer")
try req.fileio.writeFile(data, at: "/path/to/file.txt").wait()

Parameters

path String

Path to file on the disk.

buffer Byte​Buffer

The ByteBuffer to write.

Returns

Future that will complete when the file write is finished.