| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- //
- // HttpHandlers+Files.swift
- // Swifter
- //
- // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
- //
- import Foundation
- extension HttpHandlers {
-
- public class func shareFilesFromDirectory(_ directoryPath: String) -> (HttpRequest -> HttpResponse) {
- return { r in
- guard let fileRelativePath = r.params.first else {
- return .NotFound
- }
- let absolutePath = directoryPath + "/" + fileRelativePath.1
- guard let file = try? File.openForReading(absolutePath) else {
- return .NotFound
- }
- return .RAW(200, "OK", [:], { writer in
- var buffer = [UInt8](repeating: 0, count: 64)
- while let count = try? file.read(&buffer) where count > 0 {
- writer.write(buffer[0..<count])
- }
- file.close()
- })
- }
- }
-
- public class func directoryBrowser(_ dir: String) -> (HttpRequest -> HttpResponse) {
- return { r in
- guard let (_, value) = r.params.first else {
- return HttpResponse.NotFound
- }
- let filePath = dir + "/" + value
- let fileManager = NSFileManager.defaultManager()
- var isDir: ObjCBool = false
- guard fileManager.fileExists(atPath: filePath, isDirectory: &isDir) else {
- return HttpResponse.NotFound
- }
- if isDir {
- do {
- let files = try fileManager.contentsOfDirectory(atPath: filePath)
- var response = "<h3>\(filePath)</h3></br><table>"
- response += files.map({ "<tr><td><a href=\"\(r.path)/\($0)\">\($0)</a></td></tr>"}).joined(separator: "")
- response += "</table>"
- return HttpResponse.OK(.Html(response))
- } catch {
- return HttpResponse.NotFound
- }
- } else {
- if let content = NSData(contentsOfFile: filePath) {
- var array = [UInt8](repeating: 0, count: content.length)
- content.getBytes(&array, length: content.length)
- return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
- }
- return HttpResponse.NotFound
- }
- }
- }
- }
|