图像未通过目标 C 中的 POST 上传到服务器
Posted
技术标签:
【中文标题】图像未通过目标 C 中的 POST 上传到服务器【英文标题】:Image Not uploading to server by POST in Objective C 【发布时间】:2016-04-21 10:22:15 【问题描述】:我正在使用 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”,但该文件中没有任何内容。
【问题讨论】:
不工作是什么意思?您是否在服务器部分读取了一些数据?您的 ios 代码是否属于失败案例?有什么错误?日志控制台说什么?是否允许应用程序传输安全性? 请输入您遇到的错误 服务器端未收到数据和图像。 isset($_FILES) 中没有任何内容。我正在服务器上创建文件“newfile.txt”,但该文件中没有任何内容。 请验证 App Transport Security 在***.com/questions/32634738/…阅读我的回答 是允许应用程序传输安全性。 【参考方案1】:// 用于 Objective-c 代码 - 将 uiimage 转换为 nsdata // ---- // 注意:在 php 端进行编码,用于将 json 字符串转换为图像,在 google 中很容易找到 // ---
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);
【讨论】:
感谢您的回答,但我需要修改我当前的代码。我不想使用其他代码。【参考方案2】:我已使用以下代码上传图片,我认为它可能会有所帮助-
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];
【讨论】:
不,我没有使用 AFHTTPSessionManager。以上是关于图像未通过目标 C 中的 POST 上传到服务器的主要内容,如果未能解决你的问题,请参考以下文章
图像未通过 IOS 中的 POST 方法发送到 PHP Web 服务
Android 相机图像未上传到服务器。使用多部分数据 Http post