Просмотр исходного кода

First attempt at image upload. Need to set image = to WorkingDirectory+Images+UUID.png. Then upload id and image to complete process.

v2_uploadImages
admin 2 лет назад
Родитель
Сommit
9ccee49e92
4 измененных файлов: 67 добавлений и 6 удалений
  1. +28
    -2
      Sources/App/Controllers/FuelEntryController.swift
  2. +14
    -0
      Sources/App/Migrations/CreateFuelEntry.swift
  3. +4
    -4
      Sources/App/Models/FuelEntry.swift
  4. +21
    -0
      Sources/App/routes.swift

+ 28
- 2
Sources/App/Controllers/FuelEntryController.swift Просмотреть файл

@@ -12,6 +12,7 @@ struct FuelEntryController: RouteCollection {
let fuelEntries = routes.grouped("fuel_entries")
fuelEntries.get(use: index)
fuelEntries.post(use: create)
fuelEntries.post("upload-image", use: uploadImage)
fuelEntries.group(":fuelEntryID") { fuelEntry in
fuelEntry.delete(use: delete)
}
@@ -20,13 +21,13 @@ struct FuelEntryController: RouteCollection {
func index(req: Request) async throws -> [FuelEntry] {
try await FuelEntry.query(on: req.db).all()
}
func create(req: Request) async throws -> [FuelEntry] {
let fuelEntry = try req.content.decode([FuelEntry].self)
try await fuelEntry.create(on: req.db)
return fuelEntry
}
func delete(req: Request) async throws -> HTTPStatus {
guard let fuelEntry = try await FuelEntry.find(req.parameters.get("fuelEntryID"), on: req.db) else {
throw Abort(.notFound)
@@ -34,6 +35,31 @@ struct FuelEntryController: RouteCollection {
try await fuelEntry.delete(on: req.db)
return .noContent
}
func uploadImage(req: Request) async throws -> FuelEntry {
let fuelEntryID: UUID = try req.parameters.require("id")
let file = try await req.content.decode(File.self)
let filename = fuelEntryID.uuidString + ".png" // Generate a unique filename for the uploaded image
let directory = DirectoryConfiguration.detect().workingDirectory + "Images/"
if let imageData = file.data.getData(at: 0, length: file.data.readableBytes) {
do {
try Data(imageData).write(to: URL(fileURLWithPath: directory + filename)) // Save the uploaded image to server
} catch {
throw Abort(.internalServerError, reason: "Failed to save image file")
}
// Update FuelEntry model after saving the image
if let fuelEntry = try await FuelEntry.find(fuelEntryID, on: req.db) {
return fuelEntry
} else {
throw Abort(.notFound, reason: "FuelEntry not found")
}
} else {
throw Abort(.badRequest, reason: "Failed to extract image data")
}
}
}




+ 14
- 0
Sources/App/Migrations/CreateFuelEntry.swift Просмотреть файл

@@ -52,3 +52,17 @@ struct AddLatitudeAndLongitudeAndRemoveGpsLocationAndImage: AsyncMigration {
}
}

struct AddImageBackIn: AsyncMigration {
func prepare(on database: Database) async throws {
try await database.schema("fuel_entries")
.field("image", .string)
.update()
}

func revert(on database: Database) async throws {
try await database.schema("fuel_entries")
.deleteField("image")
.update()
}
}


+ 4
- 4
Sources/App/Models/FuelEntry.swift Просмотреть файл

@@ -26,8 +26,8 @@ final class FuelEntry: Model, Content {
@Field(key: "longitude")
var longitude: Double

// @Field(key: "image")
// var image: String
@Field(key: "image")
var image: String?

@Field(key: "product")
var product: String
@@ -55,13 +55,13 @@ final class FuelEntry: Model, Content {

init() {}

init(id: UUID? = nil, timestamp: Date, userID: String, latitude: Double, longitude: Double, product: String, make: String, model: String, serialNumber: String, tankID: String, fuelAmount: Double, fuelType: String, isOverride: Bool) {
init(id: UUID? = nil, timestamp: Date, userID: String, latitude: Double, longitude: Double, image: String?, product: String, make: String, model: String, serialNumber: String, tankID: String, fuelAmount: Double, fuelType: String, isOverride: Bool) {
self.id = id
self.timestamp = timestamp
self.userID = userID
self.latitude = latitude
self.longitude = longitude
// self.image = image
self.image = image
self.product = product
self.make = make
self.model = model


+ 21
- 0
Sources/App/routes.swift Просмотреть файл

@@ -29,6 +29,27 @@ func routes(_ app: Application) throws {
app.delete("fuel-entries", ":fuelEntryID") { req in
try await fuelEntryController.delete(req: req)
}
// V2 API routes with image upload
let v2Routes = app.group("api", "v2") { v2 in
let fuelEntryController = FuelEntryController()
v2.get("fuel-entries") {req in
try await fuelEntryController.index(req: req)
}
v2.post("fuel-entries") {req in
try await fuelEntryController.create(req: req)
}
v2.post("fuel-entries", ":id", "upload-image") { req -> FuelEntry in
return try await fuelEntryController.uploadImage(req: req)
}
v2.delete("fuel-entries", ":fuelEntryID") { req in
try await fuelEntryController.delete(req: req)
}
}
}



Загрузка…
Отмена
Сохранить