图像未通过目标 C 中的开机自检上传到服务器


Image Not uploading to server by POST in Objective C

我正在使用POST方法和multipartMethod将图像从iPhone上传到服务器。我的 Objective-C 代码是

__weak AuthAPIClient *client = [AuthAPIClient sharedClient];
    [client setParameterEncoding:AFJSONParameterEncoding];
    [client registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [SVProgressHUD showWithStatus:@"Saving data to server..."];
    [SVProgressHUD show];
    if ([self isInternetAvailable]) {
    NSString *userId =[[AppSettings sharedAppSettings] getUserName];
    NSString*replacedName=[userId stringByReplacingOccurrencesOfString:@" " withString:@"-"];
        NSDictionary *parametersDic = @{@"user_name":userName,@"image_data":[NSString stringWithFormat:@"uploads/%@.jpeg",replacedName]};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parametersDic options:0 error:nil];
    id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

    /////////////////////////////Test code////////////////////////////////
    NSData *imageToUpload = UIImageJPEGRepresentation(imagedata, 1.0);///imagedata is an UIImage passing in parameter of method.
    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"update_profile.php" parameters:json constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData: imageToUpload name:@"file" fileName:[NSString stringWithFormat:@"%@.jpeg",userId] mimeType:@"image/jpeg"];
    }];
    /////////////////////////////////////////////////////////////////////
    NSLog(@"response request %@",request);
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
                }];
 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //             [SVProgressHUD dismiss];
         NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
         NSLog(responseString);
         if (responseString != nil && ![responseString isEqualToString:@""] &&  operation.response.statusCode == 200) {
             NSError *error;
             // NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
             NSMutableArray* jsonArray = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
             NSLog(@"hello response %@",responseString);
         }
         else {
             NSLog(@"hello response failr %@",responseString);
             if ([self.delegate respondsToSelector:@selector(serviceHelperSavePersonalInfoDataWithDetailsFailed:error:)]) {
                 [self.delegate serviceHelperSavePersonalInfoDataWithDetailsFailed:self error:@"No Response Recieved."];
             }
         }
     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         NSLog(@"Error");
                                         //                                             [SVProgressHUD dismiss];
                                         NSMutableString *errorMsg = [[NSMutableString alloc] init];
                                         [errorMsg appendString:@"Error Occured"];
                                         if(operation.response == nil)
                                         {
                                             [errorMsg appendString:@"Service not available. Please try again"];
                                         }
                                         else if (operation.response.statusCode == 500) {
                                             [errorMsg appendString:@"Service not available. Please try again"];
                                         }
                                         else if (operation.response.statusCode == 403) {
                                             [errorMsg appendString:@"Request forbidden. Please try again"];
                                         }
                                         else {
                                             NSData *jsonData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
                                             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                                                  options:0
                                                                                                    error:nil];
                                             if (json != nil) {
                                                 [errorMsg appendString:[json objectForKey:@"message"]];
                                             }
                                         }
                                         [errorMsg appendString:@" service is not available."];
                                         if ([self.delegate respondsToSelector:@selector(serviceHelperSavePersonalInfoDataWithDetailsFailed:error:)]) {
                                             [self.delegate serviceHelperSavePersonalInfoDataWithDetailsFailed:self error:errorMsg];
                                         }
                                     }];
    [operation start];
}
else {
    if ([self.delegate respondsToSelector:@selector(serviceHelperSavePersonalInfoDataWithDetailsFailed:error:)]) {
        [self.delegate serviceHelperSavePersonalInfoDataWithDetailsFailed:self error:@"Internet not available."];
    }
}

我的PHP文件(update_profile.php)代码是

<?php
require_once "DatabaseConnection.php";
 $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
 $txt = "not set";
 if(isset($_FILES)){
   $txt = serialize($_FILES); 
   $result = "hellll";
}
 fwrite($myfile, $txt);
 fclose($myfile);
 $uploaddir = 'uploads/';
     $file = basename($_FILES['file']['name']);
     $uploadfile = $uploaddir . $file;
     if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
   // sendResponse(200, 'Upload Successful');
    //return true;
     }

我已经在其他项目中使用了相同的代码,这些代码运行良好,但在此项目中不起作用。EL Capitan OSX有关系吗?因为我已经更新了我的操作系统。 有人知道我错在哪里吗?任何帮助将不胜感激。谢谢。

错误是:服务器端未收到数据和图像。isset($_FILES)中没有任何内容,我还检查了$ _POST和$ _REQUEST但服务器没有收到任何东西,只有"a:0{}"保存在"newfile.txt"中。我正在服务器上创建文件"newfile.txt",但此文件中没有任何内容。

//对于 Objective-c 代码 - 将 uiimage 转换为 nsdata// ----注意:在php端进行编码,将json字符串转换为图像,在谷歌中轻松找到// ---

NSData *data1 = UIImageJPEGRepresentation(imgProfileView.image,0.8);  //0.1 to 1.0 upto image resolution
NSString *encodedString1 =   [data1 base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSMutableDictionary *dicImage=[[NSMutableDictionary alloc] init];
[dicImage setObject:encodedString1 forKey:@"image1"];
[dicImage setObject:[dic valueForKey:@"des1"] forKey:@"des1"]; // if added any extra filed then
NSMutableDictionary *dic_set_Sync=[[NSMutableDictionary alloc] init];
[dic_set_Sync setObject:APPDELEGATE.strEmailId forKey:@"email"];
[dic_set_Sync setObject: dicImage forKey:@"compressor_sync"];

NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dic_set_Sync options:0 error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error)
    NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);
NSURL *url = [NSURL URLWithString:@"https://www.inspectab.com/app/webservice/offline/compressor_syc.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *params = [NSString stringWithFormat:@"json=%@",
                    [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:paramsData];
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
    NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);
// examine the response
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);
if(![responseString isEqualToString:@""])
{
    NSDictionary *dicResponse = [NSJSONSerialization JSONObjectWithData:returnData
                                                                options:kNilOptions error:&error];
    NSLog(@"dicResponse: %@", dicResponse);
}

我使用以下代码上传图像,我认为这可能会有所帮助-

   NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]  multipartFormRequestWithMethod:@"POST" URLString:@“youUrl” parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.png" mimeType:@"image/png"];
} error:nil];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress) {
                  // This is not called back on the main queue.
                  // You are responsible for dispatching to the main queue for UI updates
                  dispatch_async(dispatch_get_main_queue(), ^{
                      //Update the progress view
                      //  [self.progressView setProgress:uploadProgress.fractionCompleted];
                      NSLog(@"Proggress%f",uploadProgress.fractionCompleted);
                  });


              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                      [HUD setHidden:YES];
                      UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"Please check Internet Connection!" message:@"Error" preferredStyle:UIAlertControllerStyleAlert];
                      UIAlertAction *ok=[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
                      [alert addAction:ok];
                      [self presentViewController:alert animated:YES completion:nil];
                  } else {

                      // [HUD show:NO];
                      [HUD setHidden:yes];
                      NSLog(@"%@ %@", response, responseObject);
                  }
              }];
[uploadTask resume];