How to read and write images to web root directory in Perfect-Swift?

421 Views Asked by At

I have hosted a Perfect-Swift web application in a Ubuntu Linux server. I'm looking for a way to read an image file from the web root directory and convert it to base64 compatible string to send in the response.

1

There are 1 best solutions below

1
On BEST ANSWER

I think something like this should work:

func yourHandler(request: HTTPRequest, _ response: HTTPResponse) {

   let thisFile = File(Dir.workingDir.path + "21serfing.jpg")
   if let bytes = try? thisFile.readSomeBytes(count: thisFile.size) {
      let data = Data(bytes: bytes)
      let base64Data = data.base64EncodedString()

      response.appendBody(string: base64Data)
      response.completed()
      return

   }

}

don't forget to import PerfectLib