How send NSData using POST from a iOS application?

梦想与她 提交于 2019-11-28 03:50:42

问题


NSData *imageData = UIImagePNGRepresentation(image);

How send imageData using POST?


回答1:


The following code should help

NSData *imageData = UIImagePNGRepresentation(image);

NSURL *yourURL = ...
NSMutableURLRequest *yourRequest = [NSMutableURLRequest requestWithURL:yourURL 
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                                       timeoutInterval:60.0];
//Set request to post
[yourRequest setHTTPMethod:@"POST"];

//Set content type 
[yourRequest setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];

// Set authorization header if required
...

// set data
[yourRequest setHTTPBody:imageData];


// create connection and set delegate if needed
NSURLConnection *yourConnection = [[NSURLConnection alloc] initWithRequest:yourRequest 
                                                                  delegate:self
                                                          startImmediately:YES];

Please note that, it is assumed that you are using ARC.




回答2:


You can check this answer, if you are okay with using NSURLConnection https://stackoverflow.com/a/10750428/591951

This post explains how to POST an Audio file, but you can upload any file using the same method




回答3:


You can use ASIHTTPRequest library: http://allseeing-i.com/ASIHTTPRequest/

Then it's pretty easy:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

// Upload an NSData instance
[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];

Info on how to use: http://allseeing-i.com/ASIHTTPRequest/How-to-use



来源:https://stackoverflow.com/questions/10753099/how-send-nsdata-using-post-from-a-ios-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!