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"])
}
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)
}
}
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.