我在我当前的应用程序中使用multipart的上传方法正在运行,但是,我正在使用Alamofire 4进行Get和Post方法,并且我想使用Alamofire的多部分功能来上传文件我可以在UI中使用完成结果。
但我无法将当前代码转换为成功使用Alamofire。
基本上,当前代码会创建包含自定义边界的整个多部分格式,并将其全部激活到URL正文中。但我似乎无法在Alamofire中重现这一点?
我目前的代码如下:
pollServer() { (liveServer) -> () in
let boundary = "----------Boundary\(sUUID)"
let methodURL : String = String(format: "https://\(liveServer)/\(methodName)")
// create url request to send
var mutableURLRequest = NSMutableURLRequest(url: NSURL(string: methodURL)! as URL)
mutableURLRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
let boundaryConstant = boundary
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpShouldHandleCookies = false
mutableURLRequest.timeoutInterval = 30
mutableURLRequest.cachePolicy = .reloadIgnoringLocalCacheData
mutableURLRequest.httpMethod = "POST"
//-- Append data into posr url using following method
let uploadData = NSMutableData()
//-- "sUUID" is keyword from service
uploadData.append("--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"sUUID\"\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("\(sUUID)".data(using: String.Encoding.utf8)!)
uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
//-- For sending image into service if needed (send image as imagedata)
uploadData.append("Content-Disposition: form-data; name=\"files[]\"; filename=\"\(fileName)\"\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Type: application/octet-stream\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append(sStream)
//-- "sEvent" is keyword form service
uploadData.append("\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"nEventID\"\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("\(EventID)".data(using: String.Encoding.utf8)!)
//-- "sExt" is keyword form service
uploadData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"sExt\"\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("\(sExt)".data(using: String.Encoding.utf8)!)
uploadData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
mutableURLRequest.httpBody = uploadData as Data
let postLength = "\(UInt(uploadData.length))"
mutableURLRequest.setValue(postLength, forHTTPHeaderField: "Content-Length")
mutableURLRequest.url = NSURL(string: methodURL) as URL?
let session = URLSession.shared
let task = session.dataTask(with: mutableURLRequest as URLRequest, completionHandler: {data, response, error -> Void in
print("Response: \(response)")
print("Data: \(data?.description)")
print("Error: \(error?.localizedDescription)")
}
)
task.resume()
}