Upload Image to the PHP Server from iOS

Upload image to the PHP server from iOS

You can upload image from iOS App to PHP server like this two way:

Using New AFNetworking :

#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"

NSString *stringUrl =@"http://www.myserverurl.com/file/uloaddetails.php?"
NSString *string =@"http://myimageurkstrn.com/img/myimage.png"
NSURL *filePath = [NSURL fileURLWithPath:string];

NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:userid,@"id",String_FullName,@"fname",String_Email,@"emailid",String_City,@"city",String_Country,@"country",String_City,@"state",String_TextView,@"bio", nil];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:filePath name:@"userfile" error:nil];//here userfile is a paramiter for your image
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"%@",[responseObject valueForKey:@"Root"]);
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:string delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];

}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];

}];

Second use NSURLConnection:

-(void)uploadImage
{
NSData *imageData = UIImagePNGRepresentation(yourImage);

NSString *urlString = [ NSString stringWithFormat:@"http://yourUploadImageURl.php?intid=%@",1];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

This both way working fine for uploading image from app to php server hope this helps for you.

Upload image to PHP web server from iOS

You can use AFNetworking framework (https://github.com/AFNetworking/AFNetworking), it will save a lot of time for you and there are some examples how to upload images and handle responses.

Here is an example of file upload from the source mentioned above:

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

Uploading Images using ios to php

You should take unique file name for every image like timestamp which will always be unique.

in below line you are setting image name so set it with time stamp.

 [body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

You can kepp unique name aomething like this which i have used once,

            NSDate *currentDate = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSString* cleanedString = [[localDateString stringByReplacingOccurrencesOfString:@"." withString:@""]stringByReplacingOccurrencesOfString:@":" withString:@""];
NSString *cleanedString2 = [cleanedString stringByAppendingFormat:@"%d",i];
NSString *finalUniqueImageNAme = [cleanedString2 stringByAppendingString:@".jpg"];

Hope this will help ;)

Update :

you can use unique name like this,

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];

And second thing you should use AFNetworking to do this kind of stuff. it'll manage all this kind of stuff like set boundary etc. Click here for AFNetworking github

Update 2 (according to query of comment):

You should use NSURLSession instead of nsurlconnection because connection is deprecated now so your code should be like this

 NSURLSession *session = [NSURLSession sharedSession];

[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

if (data) {

//if response is in string format
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

//if response in json format then
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

}

}]resume];

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 field
  • photo-name a text field
  • photo-description a text field
  • contest-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 the boundary 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()
}

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.



Related Topics



Leave a reply



Submit