1
0

HttpHandlers+Files.swift~ 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // HttpHandlers+Files.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. extension HttpHandlers {
  9. public class func shareFilesFromDirectory(_ directoryPath: String) -> (HttpRequest -> HttpResponse) {
  10. return { r in
  11. guard let fileRelativePath = r.params.first else {
  12. return .NotFound
  13. }
  14. let absolutePath = directoryPath + "/" + fileRelativePath.1
  15. guard let file = try? File.openForReading(absolutePath) else {
  16. return .NotFound
  17. }
  18. return .RAW(200, "OK", [:], { writer in
  19. var buffer = [UInt8](repeating: 0, count: 64)
  20. while let count = try? file.read(&buffer) where count > 0 {
  21. writer.write(buffer[0..<count])
  22. }
  23. file.close()
  24. })
  25. }
  26. }
  27. public class func directoryBrowser(_ dir: String) -> (HttpRequest -> HttpResponse) {
  28. return { r in
  29. guard let (_, value) = r.params.first else {
  30. return HttpResponse.NotFound
  31. }
  32. let filePath = dir + "/" + value
  33. let fileManager = NSFileManager.defaultManager()
  34. var isDir: ObjCBool = false
  35. guard fileManager.fileExists(atPath: filePath, isDirectory: &isDir) else {
  36. return HttpResponse.NotFound
  37. }
  38. if isDir {
  39. do {
  40. let files = try fileManager.contentsOfDirectory(atPath: filePath)
  41. var response = "<h3>\(filePath)</h3></br><table>"
  42. response += files.map({ "<tr><td><a href=\"\(r.path)/\($0)\">\($0)</a></td></tr>"}).joined(separator: "")
  43. response += "</table>"
  44. return HttpResponse.OK(.Html(response))
  45. } catch {
  46. return HttpResponse.NotFound
  47. }
  48. } else {
  49. if let content = NSData(contentsOfFile: filePath) {
  50. var array = [UInt8](repeating: 0, count: content.length)
  51. content.getBytes(&array, length: content.length)
  52. return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
  53. }
  54. return HttpResponse.NotFound
  55. }
  56. }
  57. }
  58. }