2015-11-08 62 views
0

我正在使用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]; 
} 

至於默劇類型是關注,image/jpeg應該由WordPress得到支持。除非C:\\Windows\\Temp\\phpF010.tmp不是一個真實的圖像,然後AFNetworking發送一個損壞的文件? 任何人都可以提供這方面的建議嗎?提前致謝。

回答

0

$wp_filetype['proper_filename']會返回什麼嗎?我沒有嘗試過,但我認爲這應該返回文件名,因爲它應該是(即擴展名)。如果是這樣,你應該將上傳的文件移動到另一個位置,然後用新文件名重新命名,上傳應該成功。

+0

'$ wp_filetype ['proper_filename']'返回'0'在我的情況。所以我猜這是不正確的文件? –

+0

聽起來像這樣。我不熟悉AFNetworking,但發現[this](http://stackoverflow.com/questions/27513684/afnetworking-2-image-upload-request-failed-unsupported-media-type-415)。不知道它是否有幫助。 – Zakalwe