[英]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: 这是代码,addVideo是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: vapor 2.0服务器代码:
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
. 从您的Multipart.File
获取Bytes
并转换为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. 您可以从File
对象获取FILENAME或创建自己的File
。
While other answers explained how to save data as file, the following code shows how to save data as database blob: 其他答案解释了如何将数据另存为文件时,以下代码显示了如何将数据另存为数据库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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.