dongyao5186 2015-11-08 10:31
浏览 81

无法识别的图像文件类型

I'm creating an iOS application using AFMultipartFormData AFNetworking to upload an image onto Wordpress site. On the Wordpress server side, the following data was received when I echoed $_FILES:

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

Somehow, Wordpress doesn't recognize my file as a valid image file in wp_check_filetype_and_ext() as I'm getting the following error back:

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

Here is my Wordpress function to handle the file uploaded and insert it into the media directory:

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;
}

Here is the code on the front-end to send the image:

- (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];
}

As far as the mimes type is concern, image/jpeg should be supported by wordpress. Unless C:\\Windows\\Temp\\phpF010.tmp is not a true image, then AFNetworking is sending a corrupted file? Can anyone offer advice on this? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongqie8661 2015-11-08 15:41
    关注

    Does $wp_filetype['proper_filename'] return something? I haven't tried this but I think this should return the filename as it should be (i.e. with an extension). If it does, you should move the uploaded file to another location and then rename it with the new filename, the upload should then succeed.

    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程