【发布时间】:2026-01-28 20:30:01
【问题描述】:
这次我在 iphone 上做一些上传的东西。这对我来说绝对是第一次。
我通过谷歌搜索并在 * 上找到了一些有用的链接和答案。
我可以通过以下代码上传图片:
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90);
NSString *urlString = @"server-url";
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc]init] autorelease];
[request setTimeoutInterval:60.0];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file\";filename=\"myfile.jpg\"\r\n"]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//NSString * dataLength = [NSString stringWithFormat:@"%d", [body length]];
//[request addValue:dataLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:body];
NSLog(@"%@",[[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding]);
但我对上述代码的工作方式有很多疑问,比如边界是什么,它的格式是什么?什么是内容处置等等。
我在谷歌上搜索了很多以了解发布请求的格式,但没有找到任何准备好的代码代码可以工作吗?
【问题讨论】:
标签: iphone iphone-sdk-3.0 post httprequest