send image to the server from iPhone and store it on the server using restful

♀尐吖头ヾ 提交于 2019-12-12 02:27:11

问题


I create an iPhone application where the use should subscribe before using it. While subscribing he should add his picture from the galerie, My problem is how to send that picture to the server side via a POST methode, I'm using restful webservices, and after recuperate it from the server side how can I store it on the server.

Any help would be very appreciated Thank you a lot in advence.


回答1:


Using NSMutableURLRequest you can upload image to server

-(void)uploadImage
{
    NSString *strURL =@"your server url";// Url server
    UIImage *img = [UIImage imageNamed:@"image.png"];
    NSData *file1Data = UIImagePNGRepresentation(img);
    NSString *name=[NSString stringWithFormat:@"image.png"];
    // NSData *file1Data = [NSData dataWithContentsOfURL:recordedTmpFile];

    //Create web Service
    // NSString *urlString = @”http://demos.nanostuffs.com/iphone/audio.php”;

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:[NSURL URLWithString:strURL]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------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:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",name]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:file1Data]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding] ;
}


来源:https://stackoverflow.com/questions/18895311/send-image-to-the-server-from-iphone-and-store-it-on-the-server-using-restful

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