1

我目前正在通过 HTTP Post 上传文件,使用[body appendData: [NSData dataWithData:data]];where data 是我的文件的 NSMutableData 表示。

// Set content type to be form data
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

// Set content type to be form data
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

// Set up web request with HTTP post headers for 1 form field which is the image
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding: NSUTF8StringEncoding]];
[body appendData: [NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding: NSUTF8StringEncoding]];

// Set the body
[request setHTTPBody: body];

由于内存限制,我已经读过最好使用setHTTPBodyStream和传递文件在磁盘上的位置上传 - 我将如何使用这种方法设置其他属性,例如内容处置?

4

1 回答 1

3

您必须准备一个包含整个 HTML 请求正文的文件,包括多部分边界、内容类型和处置,并将其用于setHTTPBodyStream.

还有其他替代方案(子类NSInputStream化,这似乎有点棘手,还有 3rd 方库,例如 ASIHTTPRequest)。这篇文章提供了更多信息和链接。

于 2012-07-27T18:31:00.663 回答