Запрос не выполнен: недопустимый тип контента: image / jpg с использованием AFNetworking 2.5

Я знаю, что этот вопрос уже задавался несколько раз в переполнении стека. Но я все еще смущаюсь по этому поводу. Я пытался использовать

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"image/jpg", nil];

Но я все еще получал ошибку, пока я не добавил заголовок («Content-type: application / json»); в моем PHP-файле. Но в моем php-файле нет структуры jason.

Моя сторона ios:

AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

NSError *__autoreleasing* error;
// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://192.168.199.118/search.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:@"uploadedfile"fileName:@"image.jpg"mimeType:@"image/jpg"];
} error:(NSError *__autoreleasing *)error];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"image/jpg", nil];

AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure %@", error.description);
if (error.code == -1001) {
[self NetworkAlert:@"Resquest timed out. Please try again and check your network connection."];

}
}];

Моя сторона php:

<?php

#function for streaming file to client
function streamFile($location, $filename, $mimeType='image/jpg')
{ if(!file_exists($location))
{ header ("HTTP/1.0 404 Not Found");
return;
}

//header("Content-Type: $mimeType");
header("Content-type:application/json");
readfile($location);

}

#**********************************************************
#Main script
#**********************************************************
header("Content-type:application/json");
#<1>set target path for storing photo uploads on the server
$photo_upload_path = "upload/";
$photo_upload_path = $photo_upload_path.basename( $_FILES['uploadedfile']['name']);
$photo_upload_indicator_path = "upload/image_ready";

#<2>set target path for storing result on the server
$downloadFileName = 'processed_';
$processed_photo_output_path = "output/processed_";
$processed_photo_output_path = $processed_photo_output_path.basename( $_FILES['uploadedfile']['name']);
$processed_photo_output_indicator_path = "output/result_ready";
$downloadFileName = $downloadFileName.basename( $_FILES['uploadedfile']['name']);

#<3>modify maximum allowable file size to 10MB and timeout to 300s
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);

#<4>Get and stored uploaded photos on the server
if(copy($_FILES['uploadedfile']['tmp_name'], $photo_upload_path)) {

#<5>signal that the image is ready
$handle = fopen($photo_upload_indicator_path, 'w');
fprintf($handle, '%s', $photo_upload_path);
fclose($handle);

#<6>wait until the result is ready
while (!file_exists($processed_photo_output_indicator_path))
{
usleep(1000000);
}
usleep(1000000);
unlink($processed_photo_output_indicator_path);

#<7>stream processed photo to the client
streamFile($processed_photo_output_path, $downloadFileName,'image/jpg');
} else{
echo "There was an error uploading the file to $photo_upload_path !";
}

?>

Заголовок («Content-type: application / json»); помогает мне решить проблему. Но я не знаю почему.
И если удалить этот код, я всегда получу «ошибка запроса не удалось». И если я хочу получить некоторую информацию с php-сервера с изображением, какой путь лучше? Большое спасибо за любые советы.

2

Решение

Ваш PHP-скрипт устанавливает Content-type заголовок в строке чуть ниже комментария #Main script

Вы должны удалить это и ответить с правильным MIME-типом для вашего изображения, image/jpeg (включите «е»). AFNetworking поставляется с ответным сериализатором, AFImageResponseSerializer, который будет автоматически декодировать ответ с Content-type image/jpeg в UIImage:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFImageResponseSerializer serializer];

AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, UIImage *responseImage) {
NSLog(@"Success %@", responseImage);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure %@", error.description);
if (error.code == -1001) {
[self NetworkAlert:@"Resquest timed out. Please try again and check your network connection."];

}
}];
4

Другие решения

Других решений пока нет …