Skip to content

Instantly share code, notes, and snippets.

@wpuricz
Created February 1, 2017 14:13
Show Gist options
  • Save wpuricz/c25d71409cc00340b85d8494c0dfc16a to your computer and use it in GitHub Desktop.
Save wpuricz/c25d71409cc00340b85d8494c0dfc16a to your computer and use it in GitHub Desktop.
Multipart upload using vapor
drop.post("upload") { request in
print(request.multipart?["image"]?.file?.data)
guard let fileData = request.multipart?["image"]?.file?.data else {
throw Abort.custom(status: .badRequest, message: "No file in request")
}
let workPath = drop.workDir
let name = UUID().uuidString + ".png"
let imageFolder = "Public/images"
let saveURL = URL(fileURLWithPath: workPath).appendingPathComponent(imageFolder, isDirectory: true).appendingPathComponent(name, isDirectory: false)
do {
let data = Data(bytes: fileData)
try data.write(to: saveURL)
} catch {
throw Abort.custom(status: .internalServerError, message: "Unable to write multipart form data to file. Underlying error \(error)")
}
return try JSON(node: [
"status" : "Success"
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment