如何在单个请求中将文本和图像数据上传到服务器目标c

时间:2016-09-22 06:20:08

标签: objective-c

我正在使用此词典,但无法上传。

dictionary = @{ kRequest: sign_in_owner, o_first_name: s_fname, o_middle_name: s_mname, o_last_name: s_lname, o_email_id: s_email, o_primary_no: s_pnum, o_alternative_no: s_anum, o_project: s_proj, o_block: s_block, o_flat: s_flat, o_total_sq_ft: s_square, o_flat_intercom_no: s_intercom, o_maintenance: s_maintenance};

以下是我的其余代码:

NSMutableArray* s_photo=[dictAttributes objectForKey:kPhoto];
isPhoto=NO;
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = @"photo[]";

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@"http://-----"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in dictionary) {

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];

}

// add image data

if (s_photo) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[s_photo objectAtIndex:0]];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
 }

 [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

 // setting the body of the post to the reqeust
 [request setHTTPBody:body];

 // set the content-length
 NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];


 // set URL
 [request setURL:requestURL];

1 个答案:

答案 0 :(得分:0)

您可以使用AFNetworking Framework

它提供了一次上传文本和图像的方法(在一次服务调用中)。

NSData *imageData = UIImageJPEGRepresentation(imgAttachment, 0.5);
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://yourURL" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    if (imageData != nil) {
        [formData appendPartWithFileData:imageData name:@"param_name" fileName:@"AnyNameForImage.jpg" mimeType:@"image/jpeg"];
    }

} 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

} completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    if (error) {

            NSLog(@"ERROR : %@", error.description);
    } else {

            NSLog(@"Response Headers : %@", response);
            NSLog(@"Response Data : %@", responseObject);
    }
}];

[uploadTask resume];