我无法找到处理文件上传的任何示例,尤其是如何保存到某个特定文件夹。
以下是代码,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"])
}
答案 0 :(得分:3)
示例如下所示:
steam 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"])
}
客户代码:
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)
}
}
答案 1 :(得分:2)
从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"))
您可以从File
对象获取FILENAME,也可以自行创建。
答案 2 :(得分:1)
虽然其他答案解释了如何将数据保存为文件,但以下代码显示了如何将数据保存为数据库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()