Swift 3 upload image to PHP-Server
Change the "1" in your declare for imgData to 0.1
let imgData = UIImageJPEGRepresentation(image, 0.1)!
That changes the quality of the image uploaded. Where 1 being the highest quality and 0 being the lowest (most compressed). I had the same issue when I used "1" but worked for me when I set to a lower quality. The image quality was noticeably bad for me so this solution may work for you too. You can also try another quality/compression amount, such as 0.2 or 0.5 or higher. That may also work for you, you just have to test it.
I speculate the reason for this is that the image was too big (when not compressed) for the server to handle it.
Alamofire and PHP Upload Images
It looks like your parameter names are not matching:
The name that you use in Swift code is "image[]", but inside the PHP code it's completely different.
It should be something like
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = basename($_FILES["image"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Upload multipart image to PHP server from iOS app
Your body
data is wrong formatted for a multipart/form-data
enctype. Assuming that you want to POST the following fields:
username
a text fieldphoto-name
a text fieldphoto-description
a text fieldcontest-photo
a file field(will contain image's binary data)
Your body should look like:
--SwiftBoundary
Content-Disposition: form-data; name="username"
my username value
--SwiftBoundary
Content-Disposition: form-data; name="photo-name"
my photo-name value
--SwiftBoundary
Content-Disposition: form-data; name="photo-description"
my photo-description value
--SwiftBoundary
Content-Disposition: form-data; name="contest-photo"; filename="myfile.jpg"
Content-Type: image/jpeg
...my image binary data...
--SwiftBoundary--
You also will have to set the following headers on request:
Content-Length
to the length of body- and
Content-Type: multipart/form-data; boundary=SwiftBoundary
, here is important that theboundary
string matches the one used in body
If you manage to update your request to look like above, you will find your image data under $_FILES['contest-photo']
Your send
function should look something like this:
func send()
{
let request = NSMutableURLRequest(URL: NSURL(string: "***URL to upload.php***")!)
request.HTTPMethod = "POST"
let imageData :NSData = UIImageJPEGRepresentation(globalImage, 1.0)!;
let boundary = "SwiftBoundary"
let contentType = "multipart/form-data; boundary=\(boundary)"
let fileName = "\(globalImage.description).jpg"
let parameterName = "contest-photo"
let body = NSMutableData()
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"username\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("\(globalUsr)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"photo-name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("\(globalImage.description)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"photo-description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("\(message.text)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"\(fileName)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData)
body.appendData("\r\n--\(boundary)--".dataUsingEncoding(NSUTF8StringEncoding)!)
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request.HTTPBody = body
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString!)")
}
task.resume()
}
Related Topics
Refresh a Table with Jquery/Ajax Every 5 Seconds
How to Rotate Image and Save the Image
Reverse Geocoding with Google Map API and PHP to Get Nearest Location Using Lat,Long Coordinates
Codeigniter Send Email with Attach File
Show/Hide Fields Depending on Select Value
How to Manage a Single PHP5 Session on Multiple Apache Servers
Woocommerce: Check If Items Are Already in Cart
Get Variable from PHP File Using Jquery/Ajax
$Stmt->Execute():How to Know If Db Insert Was Successful
MySQL Get a Random Value Between Two Values
Extract a Substring Between Two Characters in a String PHP
How to Replace All Xhtml/HTML Line Breaks (<Br>) with New Lines
Explode() into $Key=>$Value Pair
PHP Linefeeds (\N) Not Working