Thanks for reading.
I am new to iOS and I am trying to upload an Image and a text using multi-part form encoding
in iOS.
The curl
I can show you an example of uploading a .txt file to a server with NSMutableURLRequest
and NSURLSessionUploadTask
with help of a php script.
-(void)uploadFileToServer : (NSString *) filePath
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://YourURL.com/YourphpScript.php"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"File Name" forHTTPHeaderField:@"FileName"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];
NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if (error || [httpResponse statusCode]!=202)
{
//Error
}
else
{
//Success
}
[defaultSession invalidateAndCancel];
}];
[uploadTask resume];
}
php Script
$value)
{
if ($FileName=="FileName")
{
$header=$value;
break;
}
}
$uploadedDir = "directory/";
@mkdir($uploadedDir);
file_put_contents($uploadedDir."/".$FileName.".txt",
$request_body.PHP_EOL, FILE_APPEND);
header('X-PHP-Response-Code: 202', true, 202);
?>