如何发布图像,音频数据以及一些参数iOS?

时间:2016-05-05 10:17:18

标签: ios objective-c xcode7 nsurlconnection

我想使用serverURL {{data发布包含语音NSMutableURLRequest的单NSURLConnection,图片和一些文字参数的delegate数据1}}。

提前致谢。

NSString *dvcToken = [[NSUserDefaults standardUserDefaults] valueForKey:@"deviceToken"];
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
// parameters to send
[_params setObject:@"842" forKey:@"office"];
[_params setObject:@"8442" forKey:@"client"];
[_params setObject:@"0" forKey:@"sub"];
[_params setObject:ofcrName forKey:@"name"];
[_params setObject:ofcrNo forKey:@"number"];// cin_out_datetime
[_params setObject:curntDateTime forKey:@"cin_out_datetime"];
if(logIn){
    [_params setObject:@"I" forKey:@"process_type"];
    logIn = false;
}else
    [_params setObject:@"0" forKey:@"process_type"];
[_params setObject:dvcToken forKey:@"device_imei"];
[_params setObject:[[UIDevice currentDevice] name] forKey:@"device_name"];
//[_params setObject:audioData forKey:@"voice"];


// 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 = @"file";

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

// 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 _params) {
    [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", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(officerImage, 1.0);
if (imageData) {
    [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:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

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

// my audio to post
NSString *audioUrl = [NSString stringWithContentsOfURL:player.url];
NSData *audiodata;
audiodata = [[NSData alloc] initWithContentsOfFile:audioUrl];
// add it to body
[body appendData:audiodata];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// final boundary
[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:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

1 个答案:

答案 0 :(得分:0)

你可以使用这种方法

-(NSMutableURLRequest *)setSingleFileMultipartRequestForUserID:(NSString *)userID serverUrl:(NSString *)url fileData:(NSData *)fileData fileName:(NSString *)fileName MIMEType:(NSString *)mimeType
    {
        NSMutableURLRequest *serverRequest = nil;

        if(userID != nil || ![[NSString stringWithFormat:@"%@",userID] isEqualToString:@""] || url != nil || ![url isEqualToString:@""] || fileData.length >4)
        {
            NSURL *URL                         = [NSURL URLWithString:url];
            NSString * lineEnd = @"\r\n";
            NSString * twoHyphens = @"--";
            NSString * boundary = [[NSUUID UUID] UUIDString];
            NSData *voiceData = nil;
            voiceData = fileData;
            if(voiceData != nil)
            {
                serverRequest = [[NSMutableURLRequest alloc] init];
                [serverRequest setTimeoutInterval:50];
                [serverRequest setURL:URL];
                [serverRequest setHTTPMethod:@"POST"];
                [serverRequest addValue:[NSString stringWithFormat:@"%@",userID] forHTTPHeaderField:@"user_id"];
                [serverRequest addValue:mimeType forHTTPHeaderField:@"mime-Type"];
                [serverRequest addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
                NSMutableData *bodyData = [[NSMutableData alloc] init];
                [bodyData appendData:[[NSString stringWithFormat:@"%@%@%@",twoHyphens, boundary,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data;  name=\"uploaded_file\"; filename=%@ %@",[fileName stringByReplacingOccurrencesOfString:@" " withString:@"_"],lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"%@", lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];

                [bodyData appendData:voiceData];

                [bodyData appendData:[[NSString stringWithFormat:@"%@", lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [bodyData appendData:[[NSString stringWithFormat:@"%@%@%@%@",twoHyphens, boundary,twoHyphens, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
                [serverRequest setHTTPBody:bodyData];
            }
        }
        return serverRequest;
    }

它返回NSMutableURLRequest对象

然后将此对象用于请求

 NSURLRequest * urlRequest2 = NSMutableURLRequest //requset get by above method
   NSURLResponse * response2 = nil;
            NSError * error2 = nil;



    NSData * data2 = [NSURLConnection sendSynchronousRequest:urlRequest2
                                                       returningResponse:&response2
                                                                   error:&error2];

 if (error2 == nil)
            {

                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
}