我正在使用 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,但服务器未收到任何仅保存在“newfile.txt”中的“a:0{}”。我正在服务器上创建文件“newfile.txt”,但此文件中没有任何内容。
最佳答案
//对于 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);
}
关于php - 图像未通过 Objective C 中的 POST 上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36766687/