【问题标题】:Upload multiple files using http POST使用 http POST 上传多个文件
【发布时间】:2011-04-19 12:53:43
【问题描述】:

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

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

我的代码是:

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

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

提前致谢。

【问题讨论】:

  • 嗨卡皮尔,我面临同样的问题。你能帮帮我吗?
  • 你在做什么?您是否尝试使用我的方式上传多个文件?如果是这样,则在添加图像数据后使用以下行:[postBody appendData:imageData]; 替换:[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];... 希望这会有所帮助
  • 如果这不起作用,请告诉我。我随时为您提供帮助
  • Kapil 我尝试了您的解决方案,但它对我不起作用,所以我将使用 ASIHTTPRequest。无论如何,谢谢。
  • 嗨,我正在使用这种方法在facebook 上发帖。这适用于单张照片。但是我想上传单张照片的数量,即使我附加了2-3张图片,这种方法也只会上传一张图片。有没有更好的方法在 iOS 的 facebook 上多次上传?

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


【解决方案1】:

这很简单。只是形成多部分的身体。假设您有要上传的文件和“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/文件名构造,提供此名称作为方法并将二进制内容加载到 NSData*。为了清楚起见,我没有列出,但如果需要,我会添加。

【讨论】:

  • 这位先生的参数是什么?
  • 这是一个包含您请求参数的字典。
【解决方案2】:

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

更新:根据下面的评论,不再维护 ASIHTTPRequest。谨慎使用此框架。其他选项为MKNetworkKitAFNetworking

【讨论】:

  • 是的,这也是一个不错的选择,但我无法更改我的整个代码。在添加图像数据后添加 "\r\n" 以使用相同的代码完成。感谢任何方式
  • 请注意,从发布到现在,ASIHTTPRequest 已被弃用。阅读本文的任何人都应谨慎行事。
  • 感谢@StevenFisher:更新了我的答案
【解决方案3】:

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

以此为界

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

【讨论】:

  • 这篇已经快一年的帖子了。如果您在我自己的问题上看到 cmets,我已经提到了我是如何解决我的问题的,这与您的答案相同。我已经使用您所说的相同方式解决了此问题(您可以查看我的评论)。无论如何,谢谢你试图帮助我..
  • 你应该接受最正确的答案;您应该能够移动您接受的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
相关资源
最近更新 更多