使用multipart / form-data objective C上传图像

时间:2016-08-20 03:40:11

标签: ios objective-c iphone

我是新的iOS开发者。我想要使​​用multipart / form-data上传图片,这是我的obj C代码,我是从邮递员那里得到的。图片是API的请求参数。我在邮递员测试它工作正常,但我在移动设备测试它没有工作,并得到HTTP 500错误,请检查我。谢谢大家。 picture API request parameters

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

1 个答案:

答案 0 :(得分: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];