iphone - 向服务器发送图像数据(NSData)

标签 iphone objective-c

我想将图像数据发送到服务器,为此,我将该数据附加到请求的 HTTP 正文中并发送了它。我正在使用以下代码。

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://developers.our-works.com/forms/TestReceiver.aspx"]];
[request setHTTPMethod:@"POST"];

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

// now lets create the body of the post 
NSMutableData *body = [NSMutableData data];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",tempFileName] dataUsingEncoding:NSUTF8StringEncoding]];
[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]];

//data into the string..... verifying............
NSString *strTest = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
NSLog(@"%@",strTest);

// setting the body of the post to the request
[request setHTTPBody:body];

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

现在我必须发送两个不同图像的 NSData。所以,只想问一下,我可以在上面的同一个主体内发送这两个不同图像的 NSData 吗? 或者,我必须为其他图像的数据编写相同的代码。

请帮我解决这个问题。谢谢。

最佳答案

一点建议:使用 Ben Copsey 的 ASIHTTPRequest 更容易将 POST 数据发送到服务器。

您不需要编写两次代码来发布两个不同的图像,只需使用不同的键插入图像两次即可。请参见下面的示例(使用 ASIHTTPRequest)

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
[request setFile:@"/Users/ben/Desktop/ben2.jpg" forKey:@"photo2"];
[request startSynchronous];

关于iphone - 向服务器发送图像数据(NSData),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5483248/

相关文章:

iphone - UIActivityIndi​​catorView 不工作(获取影响 UIActivityIndi​​catorView 的 Facebook 权限)

iphone - 当有人拥有越狱设备时,objective-c 中的序列化对象的安全性如何?

iphone - 在 PC 上使用 iPhone 摄像头作为网络摄像头

objective-c - 时间戳和减去 Objective-C

ios - 通过多个用户唯一识别 iOS 设备

objective-c - gdb 控制台的命令是什么?

iphone - iOS:如何显示登录表单?

iphone - 使用标签栏 Controller 将登录 View 添加到应用程序

ios - NSAttributedString EXC_BAD_ACCESS KERN_INVALID_ADDRESS 崩溃

ios - 在 Cordova 应用程序中通过 Objective-C 生成 PDF