Perfect 文件上傳下載

func resignRoutes() {
    // 文件上傳
    routes.add(method: .post, uri: "/upload") { (req, resp) in
        
        // 通過操作fileUploads數(shù)組來掌握文件上傳的情況
        // 如果這個POST請求不是分段multi-part類型,則該數(shù)組內(nèi)容為空
        if let uploads = req.postFileUploads , uploads.count > 0 {
            // 創(chuàng)建文件保存路徑
            let fileDir = Dir(Dir.workingDir.path + "files")
            do {
                try fileDir.create()
            } catch {
                resp.appendBody(string: "create failed")
                print(error)
            }
            
            // 創(chuàng)建一個字典數(shù)組用于檢查已經(jīng)上載的內(nèi)容
            var ary = [[String:Any]]()
            
            for upload in uploads {
                ary.append([
                    "fieldName": upload.fieldName,  //字段名
                    "contentType": upload.contentType, //文件內(nèi)容類型
                    "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 {
                    resp.appendBody(string: "remove failed")
                    print(error)
                }
                
            }
            
            
            resp.appendBody(string: "upload success")
            
            
        } else {
            resp.appendBody(string: "upload fail")
            
        }
        resp.completed()
    }
    
    
    routes.add(method: .get, uri: "/download/**") { (req, resp) in
        req.path = req.urlVariables[routeTrailingWildcardKey]!
        let handler = StaticFileHandler(documentRoot: Dir.workingDir.path + "files")
        
        handler.handleRequest(request: req, response: resp)
    }
    server.addRoutes(routes)

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容