如何使用Perfect 2.0 swift上传文件?

时间:2016-09-22 06:44:10

标签: swift perfect

我以前从未使用任何类型的服务器端语言。我开始用swift学习它。如果我问傻话,我会提前道歉。

所以这是故事

我想将文件上传到

<path to my project>/Resources/fileuplaods

我关注的是Perfect 2.0文档,这是我的代码: -

routes.add(method: .post, uri: "/webroot/uploads") { (request, response) in

let fileDir = Dir("./Resources/fileuploads")
print("fileDir - \(fileDir)")
do {
    try fileDir.create()
}
catch {
    print(error)
}

if let uploads = request.postFileUploads , uploads.count > 0 {
    var ary = [[String : Any]]()
    for upload in uploads {
        ary.append([
            "fieldName":upload.fieldName,
            "contentType":upload.contentType,
            "fileName":upload.fileName,
            "fileSize":upload.fileSize,
            "tmpFileName":upload.tmpFileName,
            ])

        let thisFile = File(upload.tmpFileName)
        do {
            let _ = try thisFile.moveTo(path: fileDir.path + upload.fileName , overWrite: true)
        }
        catch {
            print(error)
        }
    }
    print("ary - \(ary)")

}
response.setBody(string: "API Call uploads")
response.completed()
}

以下是我的输出: -

fileDir - Dir(internalPath: "./Resources/fileuploads/")
fileError(21, "Is a directory /Users/username/Documents/flone/fltwo/projname/Packages/PerfectLib-2.0.0/Sources/PerfectLib/File.swift moveTo(path:overWrite:) 286")
ary - [["contentType": "image/jpeg", "fileSize": 18587, "fileName": "", "fieldName": "", "tmpFileName": "/tmp/perfect_upload_rodB53"]]

我做错了什么?

1 个答案:

答案 0 :(得分:2)

发现问题。实际上我不想在目的地目录中添加文件名。

必须替换

thisFile.moveTo(path: fileDir.path , overWrite: true)

thisFile.moveTo(path: fileDir.path + upload.fileName , overWrite: true)