let docDir:AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] let imagePath = docDir + "/myPic.jpg" var imageData = NSData(contentsOfFile: imagePath,options: NSDataReadingOptions.DataReadingMappedIfSafe,error: nil) var parameters = [ "pic" :NetData(nsData: imageData!,filename: "customName.jpg"),"otherParm" :"Value" ] let urlRequest = self.urlRequestWithComponents("http://www.example.com/upload.PHP",parameters: parameters)
Alamofire.upload(urlRequest.0,urlRequest.1) .progress { (bytesWritten,totalBytesWritten,totalBytesExpectedToWrite) in println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)") } }
func urlRequestWithComponents(urlString:String,parameters:NSDictionary) -> (URLRequestConvertible,NSData) { // create url request to send var mutableuRLRequest = NSMutableuRLRequest(URL: NSURL(string: urlString)!) mutableuRLRequest.HTTPMethod = Alamofire.Method.POST.rawValue //let boundaryConstant = "myRandomBoundary12345" let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())" let contentType = "multipart/form-data;boundary="+boundaryConstant mutableuRLRequest.setValue(contentType,forHTTPHeaderField: "Content-Type") // create upload data to send let uploadData = NSMutableData() // add parameters for (key,value) in parameters { uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) if value is NetData { // add image var postData = value as NetData //uploadData.appendData("Content-disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // append content disposition var filenameClause = " filename=\"\(postData.filename)\"" let contentdispositionString = "Content-disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" let contentdispositionData = contentdispositionString.dataUsingEncoding(NSUTF8StringEncoding) uploadData.appendData(contentdispositionData!) // append content type //uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this. let contentTypestring = "Content-Type: \(postData.mimeType.getString())\r\n\r\n" let contentTypeData = contentTypestring.dataUsingEncoding(NSUTF8StringEncoding) uploadData.appendData(contentTypeData!) uploadData.appendData(postData.data) }else{ uploadData.appendData("Content-disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!) } } uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // return URLRequestConvertible and NSData return (Alamofire.ParameterEncoding.URL.encode(mutableuRLRequest,parameters: nil).0,uploadData) }