使用http POST上传多个文件

时间:2011-04-19 12:53:44

标签: objective-c cocoa-touch ftp http-post

我在从iPhone应用程序上使用FTP上传文件时遇到问题。

我正在向我的网络服务发送HTTP POST请求,其中包含所有必要参数。我发送两个文件,一个是图像,第二个是音频。图像正在上传,但音频不上传。 当我跟踪我的Web服务时,它只显示图像字段作为上传文件。它没有表明音频也存在。

我的代码是:

NSString *urlString = [NSString stringWithFormat:ADD_LEAD_API_URL];

NSMutableURLRequest *postRequest =  [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];



// change type to POST (default is GET)
[postRequest setHTTPMethod:@"POST"];


// just some random text that will never occur in the body
NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";

// header value
NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];

// set header
[postRequest addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];

// create data
NSMutableData *postBody = [NSMutableData data];



[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userId\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[appDelegate.objCurrentUser.userId dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];     


// message part
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"firstName\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[firstName dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

/*** My rest of string parameters are successfully added to request ***/


// media part
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"imageUrl\"; filename=\"dummy.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    // get the image data from main bundle directly into NSData object

UIImage *img= leadImage;
NSData *imageData= UIImageJPEGRepresentation(img,90);

[postBody appendData:imageData];

// Image is being uploaded

[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"recordSoundUrl\"; filename=\"%@\"\r\n", self.recordingPath] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


NSData *soundData = [NSData dataWithContentsOfFile:[appDelegate.documentDir stringByAppendingPathComponent:self.recordingPath]];
[postBody appendData:soundData];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// final boundary
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

// add body to post
[postRequest setHTTPBody:postBody];

// Asynch request
NSURLConnection *conn = [NSURLConnection connectionWithRequest:postRequest delegate:self];

如果我没有上传图片,那么它会拍摄音频。所以我只能发送一个带有请求的文件。 请帮助我,告诉我在任何地方是否错了。

提前致谢。

3 个答案:

答案 0 :(得分:7)

这很简单。只是形成多部分身体。假设您要在'params'字典中上传文件和常规参数:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlString] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:54.0];

NSMutableData* body = [NSMutableData data];

NSString* boundary = [NSString randomStringWithLength:64];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
NSData *boundaryData = [[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding];

[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
   [body appendData:boundaryData];
    // I use special simple class to distinguish file params
   if( [obj isKindOfClass:[FileUpload class]] ) {
        // File upload
        [body appendData: [[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n\r\n", key, [obj localName]] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData: [obj loadData]]; // It just return NSData with loaded file in it
        [body appendData: [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    else {
        // Regular param
        [body appendData: [[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n", key, obj] dataUsingEncoding:NSUTF8StringEncoding]]
    }
}];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:body];

现在你可以以任何方式发送它:

[NSURLConnection sendAsynchronousRequest:request
                                   queue:queueOfYourChoice
                       completionHandler:^(NSURLResponse *response, NSData *rdata, NSError *error) 

FileUpload类相当简单:它从url / filename构造,提供此名称作为方法并将二进制内容加载到NSData *中。我没有列出清晰度,但如果需要,我会补充。

答案 1 :(得分:2)

您是否考虑过使用ASIHTTPRequestASINetworkQueue发送多个文件。

更新:根据以下评论,不再维护ASIHTTPRequest。请谨慎使用此框架。其他选项包括MKNetworkKitAFNetworking

答案 2 :(得分:0)

您可能在设置边界时遇到问题。

将此作为边界

NSString boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];

并使用此

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

而不是

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