无法识别的图像文件类型

时间:2015-11-08 10:31:57

标签: php wordpress image afnetworking-2

我正在使用AFMultipartFormData AFNetworking创建一个iOS应用程序,将图像上传到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];
}

就mimes类型而言,wordpress应该支持image/jpeg。除非C:\\Windows\\Temp\\phpF010.tmp不是真实的图像,否则AFNetworking正在发送损坏的文件? 有人可以就此提供建议吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

$wp_filetype['proper_filename']会返回什么内容吗?我没有试过这个,但我认为这应该返回应该是的文件名(即带有扩展名)。如果是,您应该将上传的文件移动到另一个位置,然后使用新文件名重命名,然后上传应该会成功。