无法识别的图像文件类型

Posted

技术标签:

【中文标题】无法识别的图像文件类型【英文标题】:Unrecognized image file type 【发布时间】:2015-11-08 10:31:57 【问题描述】:

我正在创建一个 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];

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

【问题讨论】:

【参考方案1】:

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

【讨论】:

$wp_filetype['proper_filename'] 在我的情况下返回了0。所以我猜这不是正确的文件? 听起来像。我不熟悉 AFNetworking,但找到了this。不确定是否有帮助。

以上是关于无法识别的图像文件类型的主要内容,如果未能解决你的问题,请参考以下文章

tail:执行tail -f时无法识别的文件系统类型错误

如何防止用户代理显示无法识别的 mime 类型的下载窗口?

使用具有正确语法的 pandas to_datetime() 方法,无法识别的值类型:str?

如何为 Spring Boot/MVC 资源设置可识别的内容/MIME 类型?

php 无法识别的自定义帖子类型的帖子配额。一些旧主题注册Pro Sites无法识别的帖子类型,这可以用于限制

.NET Core 重定向中无法识别的参数类型 REMOTE_ADDR 和 HTTP_X_FORWARDED_FOR