Valerii Lider
Valerii Lider

Reputation: 1814

file upload using Vapor

I can't find any example of handling file upload, especially how to save into some specific folder.

Here is the code, addVideo is a HTTP POST multipart/form-data:

videos.post("addVideo") { req in

    // need to save req.multipart["video"] into /data/videos/

    return try JSON(node: ["status": 0, "message": "success"])
}

Upvotes: 2

Views: 3188

Answers (3)

superarts.org
superarts.org

Reputation: 7238

While other answers explained how to save data as file, the following code shows how to save data as database blob:

guard 
    let name = request.data["filename"]?.string, 
    let blob = request.data["file"]?.bytes
else {
    throw Abort(.badRequest, reason: "Fields 'filename' and/or 'file' is invalid")
}
let user = try request.user()
let image = try Image(filename: name, user: user, file: blob)
try image.save()

Upvotes: 1

Nemo Agoni
Nemo Agoni

Reputation: 83

example look like this:

vapor 2.0 server code:

let d =drop.grouped("file");
d.post("updateFile") { req in
  let data = Data.init(bytes: (req.data["image"]?.bytes)!)
  let picName = req.data["name"]?.string ?? String();
  try Data(data).write(to: URL(fileURLWithPath: "/Users/xx/Desktop/\(picName).jpg"))
  return try JSON(node: ["status": 0, "message": "success"])
}

Client code:

Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(imageData!, withName: "image", fileName: "pic", mimeType:"image/jpg")

        multipartFormData.append("picName".data(using: .utf8)!, withName: "name")

    }, to: "http://0.0.0.0:8083/file/updateFile") { (encodingResult) in

        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
}

Upvotes: 3

tobygriffin
tobygriffin

Reputation: 5421

From your Multipart.File get the Bytes and convert to Data.

guard let file = request.multipart?["video"]?.file else {
  return "Not found"
}
try Data(file.data).write(to: URL(fileURLWithPath: "/data/videos/FILENAME"))

You can get FILENAME from the File object or make your own.

Upvotes: 2

Related Questions