如何在iOS目标c中上传图像时发布值

时间:2017-02-27 13:49:22

标签: php ios objective-c post

我希望在目标c中将图像上传到iOS中的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,但我想将一些POST数据与此设置为PHP脚本。这是我的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;
    }
   ?>

我如何向这个可以获取$ REQUEST ['key']的变量发送值  在PHP脚本中。

1 个答案:

答案 0 :(得分:0)

试一下

-(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{


    }
}
}