Php 如何在iOS objective c中上载图像时发布值

Php 如何在iOS objective c中上载图像时发布值,php,ios,objective-c,post,Php,Ios,Objective C,Post,我想在将图像上传到iOS中objective c中的php服务器时发送一些键值对 这是我的iOS代码: request = [NSMutableURLRequest new]; request.timeoutInterval = 20.0; [request setURL:[NSURL URLWithString:URL]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------

我想在将图像上传到iOS中objective c中的php服务器时发送一些键值对 这是我的iOS代码:

request = [NSMutableURLRequest new];
request.timeoutInterval = 20.0;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:@"POST"];


NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
[request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];


NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"%@.png\"\r\n; ", [self randomStringWithLength:5]] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
UIImage *yourImage=[UIImage imageNamed:@"prem2.jpg"];
NSData *imageData = UIImagePNGRepresentation(yourImage);

[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

[request addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[body length]] forHTTPHeaderField:@"Content-Length"];

 NSError *error = nil;
NSURLResponse *responseStr = nil;
syncResData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseStr error:&error];
NSString *returnString = [[NSString alloc] initWithData:syncResData encoding:NSUTF8StringEncoding];

NSLog(@"ERROR %@", error);
//NSLog(@"RES %@", responseStr);

NSLog(@"Reture data %@", returnString);
通过此代码图像上传成功,我获得了完美的ImageURL,但我想在php脚本中设置一些POST数据。这是我的php脚本:

<?php
  $target_path1 = "uploads/";

*$REQUEST['key'];//here i am not getting value*
  /* Add the original filename to our target path.
 Result is "uploads/filename.extension" */
 $target_path1 = $target_path1 . basename( $_FILES['uploaded_file']                            [ 'name']);
 if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],      $target_path1)) {
echo "The file ".  basename( $_FILES['uploaded_file']['name']).
" has been uploaded to ".$target_path1;;
 } else{
echo "There was an error uploading the file, please try again!";
echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
echo "target_path: " .$target_path1;
    }
   ?>

如何将值发送到此变量,该变量可以是fetch$REQUEST['key']
在PHP脚本中。

试试这个

-(void)sendDataToServer
{

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
    [_params setObject:[dict objectForKey:@"id"]  forKey:@"userId"];

[_params setObject:@""  forKey:@"address"];
[_params setObject:txtCity.text  forKey:@"city"];
[_params setObject:@""  forKey:@"country"];
[_params setObject:txtemail.text  forKey:@"emailId"];
[_params setObject:txtFullName.text  forKey:@"firstName"];
[_params setObject:txtPhoneNumber.text  forKey:@"mobile"];
[_params setObject:txtState.text  forKey:@"state"];
[_params setObject:txtZipCode.text  forKey:@"zipcode"];


DLog(@"data=====>%@",_params);
[_params setObject:@"editprofile"  forKey:@"action"];


NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = @"image";

NSURL* requestURL = [NSURL URLWithString:BaseURL];


// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

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

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params)
{
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
// set URL
[request setURL:requestURL];

NSURLResponse *response = nil;
NSError *requestError = nil;

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];


if (requestError == nil)
{

    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];

    dict=json;
    DLog(@"data=====>%@",dict);

    if ([[dict objectForKey:@"status"] isEqualToString:@"Success"]==TRUE)
    {




        UIStoryboard*storyboard=[AppDelegate storyBoardType];
        DashboardVC*dsvc=(DashboardVC*)[storyboard instantiateViewControllerWithIdentifier:@"DashboardVCId"];
        [self.navigationController pushViewController:dsvc animated:YES];
                }else{


    }
}
}

试试这个

-(void)sendDataToServer
{

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
    [_params setObject:[dict objectForKey:@"id"]  forKey:@"userId"];

[_params setObject:@""  forKey:@"address"];
[_params setObject:txtCity.text  forKey:@"city"];
[_params setObject:@""  forKey:@"country"];
[_params setObject:txtemail.text  forKey:@"emailId"];
[_params setObject:txtFullName.text  forKey:@"firstName"];
[_params setObject:txtPhoneNumber.text  forKey:@"mobile"];
[_params setObject:txtState.text  forKey:@"state"];
[_params setObject:txtZipCode.text  forKey:@"zipcode"];


DLog(@"data=====>%@",_params);
[_params setObject:@"editprofile"  forKey:@"action"];


NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = @"image";

NSURL* requestURL = [NSURL URLWithString:BaseURL];


// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

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

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params)
{
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
// set URL
[request setURL:requestURL];

NSURLResponse *response = nil;
NSError *requestError = nil;

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];


if (requestError == nil)
{

    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];

    dict=json;
    DLog(@"data=====>%@",dict);

    if ([[dict objectForKey:@"status"] isEqualToString:@"Success"]==TRUE)
    {




        UIStoryboard*storyboard=[AppDelegate storyBoardType];
        DashboardVC*dsvc=(DashboardVC*)[storyboard instantiateViewControllerWithIdentifier:@"DashboardVCId"];
        [self.navigationController pushViewController:dsvc animated:YES];
                }else{


    }
}
}

我尝试了此代码,但出现了以下错误:Domain=nscocaerorrordomain code=3840“JSON文本未以数组或对象开头,允许未设置片段的选项。”UserInfo={NSDebugDescription=JSON文本未以数组或对象开头,允许未设置片段的选项。}我尝试了此代码,但出现了以下错误:Domain=nscocaerorrordomain code=3840“JSON文本未以数组或对象开头,允许未设置片段的选项。”UserInfo={NSDebugDescription=JSON文本未以数组或对象开头,允许未设置片段的选项。}