我正在尝试使用GCDWebServer读取/写入文档目录中的文件。阅读文件看起来相当简单,我几乎得到了我的需要。
我想使用POST请求写入该文件。所以我尝试为方法“POST”添加一个处理程序,但是在进程块中我似乎根本无法读取请求的主体。
如果我这样做:
webServer?.addHandler(forMethod: "POST", path: "/post", request: GCDWebServerDataRequest.self, processBlock: {request in
dump(request)
return GCDWebServerDataResponse(html: "An error occurred.")
})
将所有标题打印到控制台(在NSObject中)。但是如何在体内读取变量?
(iOS 10.3,Swift 3,XCode 8.3.2)
答案 0 :(得分:1)
self.webServer?.addHandler(forMethod: "POST", path: "/uploadfile", request: GCDWebServerMultiPartFormRequest.classForCoder(), processBlock: { (request) -> GCDWebServerResponse? in
print("ádasdnaskdnaskjd=====<")
let get = request as! GCDWebServerMultiPartFormRequest
do {
if let files = get.files {
try files.forEach({ (file) in
if let multipartFile = file as? GCDWebServerMultiPartFile {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let urlOfFile = documentsPath.appending("/\(multipartFile.fileName!)");
let url = URL(fileURLWithPath: urlOfFile)
let fileManager = FileManager.default
try fileManager.moveItem(at: URL(fileURLWithPath: multipartFile.temporaryPath), to: url);
print("URL of file: \(url)")
}
})
}
return GCDWebServerDataResponse.init(html: "")
} catch {
print(error.localizedDescription)
}
return GCDWebServerDataResponse.init(html: "")
})
您可以使用邮递员用身体(表格数据)进行测试