I can’t write the code for uploading images in any way.
Need to do this: a request is sent from the iOS application (SwiftUI) to the backend, then the file format (jpg, jpeg, png, heic) is checked in the backend, and if OK, I upload the image to the folder.
This is the code in Vapor:
func addImage(req: Request) async throws -> HTTPStatus {
let user = try await getUserByToken(req: req)
guard let profile = try await Profile.query(on: req.db)
.filter(.$user.$id == user.requireID())
.first()
else {
throw Abort(.badRequest, reason: "Profile not found")
}
let img = try req.content.decode(File.self)
let path = req.application.directory.publicDirectory + "/images/profiles/"
let fileName = try profile.requireID().uuidString + "." + (img.extension ?? "jpg")
try await req.fileio.writeFile(img.data, at: path + fileName)
return .ok
}
This is the code in iOS:
func addImage(_ image: UIImage) async throws {
guard let url = URL(string: "(url)/add-image"),
let imageData = image.jpegData(compressionQuality: 1)
else {
throw URLError(.badURL)
}
let profileImage = ProfileImage(filename: "filename.jpg", data: imageData)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Bearer (tokenManager.getToken())", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.httpBody = try JSONEncoder().encode(profileImage)
let (_, _) = try await URLSession.shared.data(for: request)
} catch {
throw error
}
}
This code downloads only jpg files. How exactly do I determine the file format?
Please help me write two methods: one for the client (iOS) and the other for the server (Vapor).
Perhaps there is some documentation/libraries for handling file formats.
P.S. Sorry for the bad English, not my native language 🙂
Эдуард Кудрявцев is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.