Uploading an image and parameters with multipart/form-data in Swift Uploading an image and parameters with multipart/form-data in Swift swift swift

Uploading an image and parameters with multipart/form-data in Swift


Don't know if this will work for what you are trying to do but we use this to upload images, the key difference is to use filename and Content-type:

[self appendBody:body data:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\".jpg\"\r\n", key]];[self appendBody:body data:@"Content-Type: image/jpeg\r\n\r\n"];[body appendData:imageData];


For any swift 2.0 JSON Request AND PHP code :- ( Manual )

    let imageData = UIImageJPEGRepresentation(userImage, 0.3)    let url:NSURL = NSURL(string: serverURL!)! // Give ur request URL    let request = NSMutableURLRequest(URL: url)    request.HTTPMethod = "POST"    let boundary = "---------------------------14737809831466499882746641449"    let contentType = "multipart/form-data; boundary=\(boundary)"    request.addValue(contentType, forHTTPHeaderField: "Content-Type")    let body = NSMutableData()    body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)    body.appendData("Content-Disposition: form-data; name=\"userfile\"; filename=\"img.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)    body.appendData("Content-Type: image/jpeg\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)    body.appendData("Content-Transfer-Encoding: binary\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)    body.appendData(imageData!)    body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)    request.HTTPBody = body

PHP Code :-

<?php//http://192.168.1.154/Contact/uploadImgwebservice.php//print the username  and password using phpecho $_POST[‘username’];echo $_POST[‘password’];//upload your file$uploaddir = ‘./uploads/’;$file = basename($_FILES[‘userfile’][‘name’]);$uploadfile = $uploaddir . $file;if (move_uploaded_file($_FILES[‘userfile’][‘tmp_name’], $uploadfile)) {    echo “http://192.168.1.154/Contact/uploads/{$file}”;}?>