I am trying to post a photo to the vapor 4 server. I am sending a Team name as a string and an image as data.
struct SendTeam: Content {
var name: String
var img: Data
}
I want to upload the photo after validating its size to be not more than 1MB, and mimetype is of type image like (jpg, jpeg, png), then resize that image to 300px*300px and finally save it to the public\uploads directory.
I am not able to figure out how to do that.
Here is my code.
func create(req: Request) async throws -> SendTeam {
let team = try req.content.decode(SendTeam.self)
let path = req.application.directory.publicDirectory + "originals/" + team.name + "-\(UUID())"
try await req.fileio.writeFile(.init(data: team.img), at: path)
if team.name.count < 4 || team.name.count > 20 {
throw Abort(.badRequest, reason: "wrong name")
}
return team
}
Code should work on ubuntu server VPS cloud instance as well.
After Two Days of Testing, I am able to do that using SwiftGD, So I came up with this .. hope it is useful.
Image Validation
The upload an resize part