0

我创建了一个 iPhone 应用程序,用户在使用它之前应该订阅它。订阅时他应该从画廊添加他的图片,我的问题是如何通过 POST 方法将该图片发送到服务器端,我正在使用 restful web 服务,在从服务器端恢复后如何将它存储在服务器。

任何帮助将不胜感激,非常感谢您。

4

1 回答 1

0

使用NSMutableURLRequest您可以将图像上传到服务器

-(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] ;
}
于 2013-09-19T13:12:16.210 回答