如何设置正确的HTTP标头和正文

时间:2012-02-29 02:47:49

标签: iphone html http post nsurlrequest

我想将图像数据对象上传到服务器(.html),文件名为(123456700.png)。

此代码没有错误,但无法上传。

设置标题

// Initial Setting
NSString *urlString = @"http://121.78.147.19/uploadfile.html";
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];  

// Set Heeader
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

// type: text/html;charset=UTF-8;
NSString *contentType = [NSString stringWithFormat:@"text/html;charset=UTF-8; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

设置Body(imgData没问题,我检查了imgData.length)

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

// Disposition: form-data, name="image" filename="123456700.png" ???
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"123456700.png\"\r\n"] 
                  dataUsingEncoding:NSUTF8StringEncoding]];

// Type: application/octet-stream ??? 
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imgData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

运行(无错误,resData是html文本数据。

NSURLResponse *response = nil;
NSError *error = nil;
NSData *resData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

=============================================== ===============================

/uploadfile.html屏幕截图(Chrome /以下信息和文字是html源代码。)

页面没问题。通过网页上传工作正常。

带有文字“파일선택”的按钮是“选择文件”按钮。

-------------------------------网页截屏------------ ----------------------------我

/uploadfile.html

1 个答案:

答案 0 :(得分:0)

  1. http正文数据的顺序错误,
  2. 内容类型错误
  3. 在此处查看更多详细规范:Form-based File Upload in HTML