2016-08-20 7 views
-3

私は新しいiOS開発者です。私はマルチパート/フォームデータで画像をアップロードしたい、これは私のobjのCコードで、私は郵便配達員からそれを得る。画像はAPIのリクエストパラメータです。私は郵便配達でテストそれはうまく動作しますが、私はモバイルでテストしていますそれは動作していないとHTTP 500エラーを取得し、私のためにそれをチェックしてください。皆さんありがとう。 picture API request parametersマルチパート/フォームデータ用の画像をアップロードするC

strURL = [NSString stringWithFormat:@"%@%@",URL,strURL]; 
NSArray *parameters = @[ @{ @"name": @"imageInfo", @"value": @"{\"user\":{\"userId\":\"165\"},\"description\":\"test description\",\"competitionId\":\"1\",\"speciesId\":\"13\",\"lng\":\"107.9296875\",\"lat\":\"15.83453574122155\",\"locationName\":\"Đại Lãnh, Đại Lộc, Quảng Nam, Vietnam\",\"originalImageName\":\"\"}" }, 
        @{ @"name": @"filenames", @"value": @"{}" }, 
        @{ @"name": @"files", @"fileName": (UIImageJPEGRepresentation(uploadImage, 0.1)) } ]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strURL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0]; 
NSString *boundary = @"---011000010111000001101001"; 
NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=---011000010111000001101001", 
          @"cache-control": @"no-cache", 
          @"postman-token": @"463bcf06-08f6-7611-c1fb-13b0dde79c5c"}; 

NSError *error; 
NSMutableString *body = [NSMutableString string]; 
for (NSDictionary *param in parameters) { 
    [body appendFormat:@"\r\n--%@\r\n", boundary]; 
    if (param[@"fileName"]) { 
     [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], @"yourimage.jpg"]; 
     [body appendFormat:@"Content-Type: image/jpeg\r\n\r\n"]; 
     [body appendFormat:@"%@", param[@"fileName"]]; 
     if (error) { 
      NSLog(@"%@", error); 
     } 
    } else { 
     [body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]]; 
     [body appendFormat:@"%@", param[@"value"]]; 
    } 
} 
[body appendFormat:@"\r\n--%@--\r\n", boundary]; 
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; 
[request setHTTPMethod:@"POST"]; 
[request setAllHTTPHeaderFields:headers]; 
[request setHTTPBody:postData]; 
NSURLResponse *response; 

NSURLSession *session = [NSURLSession sharedSession]; 
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request 
              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
               if (error) { 
                NSLog(@"%@", error); 
               } else { 
                NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
                NSLog(@"%@", httpResponse); 
               } 
              }]; 
[dataTask resume]; 
+0

500内部サーバーエラーがある、あなたは私がサーバーとウォーキングないよサーバログ – meda

+0

をチェックする必要があり、私はちょうどAPIを受け取り、それを使用しています。 – garish

答えて

3

AFNetworkingサードパーティクラスを使用できます。 参考:https://github.com/AFNetworking/AFNetworking

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; 
    } error:nil]; 

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

NSURLSessionUploadTask *uploadTask; 
uploadTask = [manager 
       uploadTaskWithStreamedRequest:request 
       progress:^(NSProgress * _Nonnull uploadProgress) { 
        // This is not called back on the main queue. 
        // You are responsible for dispatching to the main queue for UI updates 
        dispatch_async(dispatch_get_main_queue(), ^{ 
         //Update the progress view 
         [progressView setProgress:uploadProgress.fractionCompleted]; 
        }); 
       } 
       completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
        if (error) { 
         NSLog(@"Error: %@", error); 
        } else { 
         NSLog(@"%@ %@", response, responseObject); 
        } 
       }]; 

[uploadTask resume]; 
+0

ありがとうございます、私はAFNetworkingクラスを使用しますが、それでも動作しません。これは私のコードです:(。http://prntscr.com/c9onen – garish

関連する問題