Нераспознанный тип файла изображения

Я создаю приложение для iOS, используя AFMultipartFormData AFNetworking для загрузки изображения на сайт WordPress. На стороне сервера WordPress следующие данные были получены, когда я повторил $_FILES:

media = {
error = (
0
);
name = (
"IMG_0004.JPG");
"tmp_name" = (
"C:\\Windows\\Temp\\phpF010.tmp");
type =  (
"image/jpeg");
};

Почему-то WordPress не распознает мой файл как допустимый файл изображения в wp_check_filetype_and_ext() так как я получаю следующую ошибку обратно:

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unsupported media type (415)"

Вот моя функция WordPress для обработки загруженного файла и вставки его в медиа-каталог:

function ldp_image_upload( $request ) {
if ( empty($_FILES) ) {
return new WP_Error( 'Bad Request', 'Missing media file', array( 'status' => 400 ) );
}

$overrides = array('test_form' => false);
$uploaded_file = $_FILES['media'];

$wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] );
if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) )
return new WP_Error( 'Unsupported Media Type', 'Invalid image file', array( 'status' => 415 ) );

$file = wp_handle_upload($uploaded_file, $overrides);

if ( isset($file['error']) )
return new WP_Error( 'Internal Server Error', 'Image upload error', array( 'status' => 500 ) );

$url  = $file['url'];
$type = $file['type'];
$file = $file['file'];
$filename = basename($file);

// Construct the object array
$object = array(
'post_title' => $filename,
'post_content' => $url,
'post_mime_type' => $type,
'guid' => $url,
);

// Save the data
$id = wp_insert_attachment($object, $file);

if ( !is_wp_error($id) ) {
// Add the meta-data such as thumbnail
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}

// Create the response object
$response = new WP_REST_Response( array('result' => 'OK'));
return $response;
}

Вот код на внешнем интерфейсе для отправки изображения:

- (void)createMedia:(RemoteMedia *)media
forBlogID:(NSNumber *)blogID
progress:(NSProgress **)progress
success:(void (^)(RemoteMedia *remoteMedia))success
failure:(void (^)(NSError *error))failure
{
NSProgress *localProgress = [NSProgress progressWithTotalUnitCount:2];
NSString *path = media.localURL;
NSString *type = media.mimeType;
NSString *filename = media.file;

NSString *apiPath = [NSString stringWithFormat:@"sites/%@/media/new", blogID];
NSString *requestUrl = [self pathForEndpoint:apiPath
withVersion:ServiceRemoteRESTApibbPressExtVersion_1_0];

NSMutableURLRequest *request = [self.api.requestSerializer multipartFormRequestWithMethod:@"POST"URLString:[[NSURL URLWithString:requestUrl relativeToURL:self.api.baseURL] absoluteString]
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
[formData appendPartWithFileURL:url name:@"media[]" fileName:filename mimeType:type error:nil];
} error:nil];

AFHTTPRequestOperation *operation = [self.api HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *    operation, id responseObject) {
NSDictionary *response = (NSDictionary *)responseObject;
NSArray * errorList = response[@"error"];
NSArray * mediaList = response[@"media"];
if (mediaList.count > 0){
RemoteMedia * remoteMedia = [self remoteMediaFromJSONDictionary:mediaList[0]];
if (success) {
success(remoteMedia);
}
localProgress.completedUnitCount=localProgress.totalUnitCount;
} else {
DDLogDebug(@"Error uploading file: %@", errorList);
localProgress.totalUnitCount=0;
localProgress.completedUnitCount=0;
NSError * error = nil;
if (errorList.count > 0){
NSDictionary * errorDictionary = @{NSLocalizedDescriptionKey: errorList[0]};
error = [NSError errorWithDomain:WordPressRestApiErrorDomain code:WPRestErrorCodeMediaNew userInfo:errorDictionary];
}
if (failure) {
failure(error);
}
}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogDebug(@"Error uploading file: %@", [error localizedDescription]);
localProgress.totalUnitCount=0;
localProgress.completedUnitCount=0;
if (failure) {
failure(error);
}
}];

// Setup progress object
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
localProgress.completedUnitCount +=bytesWritten;
}];
unsigned long long size = [[request valueForHTTPHeaderField:@"Content-Length"] longLongValue];
// Adding some extra time because after the upload is done the backend takes some time to process the data sent
localProgress.totalUnitCount = size+1;
localProgress.cancellable = YES;
localProgress.pausable = NO;
localProgress.cancellationHandler = ^(){
[operation cancel];
};

if (progress) {
*progress = localProgress;
}
[self.api.operationQueue addOperation:operation];
}

Что касается типа мимов, image/jpeg должен быть поддержан WordPress. Если не C:\\Windows\\Temp\\phpF010.tmp не истинное изображение, то AFNetworking отправляет поврежденный файл?
Кто-нибудь может дать совет по этому поводу? Заранее спасибо.

0

Решение

Есть ли $wp_filetype['proper_filename'] вернуть что-нибудь? Я не пробовал это, но я думаю, что это должно вернуть имя файла, как это должно быть (то есть с расширением). Если это произойдет, вы должны переместить загруженный файл в другое место, а затем переименовать его с новым именем файла, загрузка должна завершиться успешно.

0

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

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

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector