图像未通过POST上传到服务器的目标C
我正在使用POST方法和multipartMethod将图像从iphone上传到服务器。我的Objective-C代码是图像未通过POST上传到服务器的目标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有关吗?因为我已更新我的操作系统。任何人有任何想法我错了?任何帮助,将不胜感激。谢谢。
错误是: 数据,并在服务器side.Nothing没有收到图像进来isset($ _ FILES)和我也有检查$ _ POST和$ _REQUEST但服务器不仅recieving什么“一:0 {}”在节约'newfile.txt'。我正在服务器上创建文件'newfile.txt',但没有任何文件。
我已用于图像上载下面的代码我认为这可以帮助 -
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。 –
//对于Objective-C代码 - 转换的UIImage到NSData的 // ---- //注:在PHP侧做编码转换JSON字符串到图像,easiliy在谷歌 // ---
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);
}
感谢您的回答,但我需要修改我当前的代码。我不想使用其他代码。 –
不工作手段发现?你读过服务器部分的一些数据吗?你的iOS代码是否属于失败案例?什么是错误?什么说日志控制台?是否允许应用传输安全? – Larme
请把错误你得到 – AnshaD
数据和图像没有收到服务器端。什么都没有进入isset($ _ FILES)。我正在服务器上创建文件'newfile.txt',但没有任何文件。 –