将图像上传到服务器

时间:2011-07-04 20:20:57

标签: iphone objective-c

我想上传一个 UIImage 到服务器。

问题我不知道如何将它添加到我的帖子到服务器。 直到现在我发送帖子与thia:

NSString *reqURL = [NSString stringWithFormat:@"url"];
    reqURL = [reqURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];

图像有什么不同的方法吗?

2 个答案:

答案 0 :(得分:0)

This answer指向this wrapper framework,这样可以轻松地执行您想要的操作,而无需处理HTTP标头字符串等。

基本上,您可以使用UIImage之类的功能将NSData转换为UIImagePNGRepresentation()对象,然后通过HTTP上传。

答案 1 :(得分:0)

使用ASIHttpRequest

-(void)uploadImage{
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

    // Upload a file on disk
    [request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg"
forKey:@"photo"];

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

  [request setDelegate:self];
  [request setDidFinishSelector:@selector(uploadRequestFinished:)];
  [request setDidFailSelector:@selector(uploadRequestFailed:)];

  [request startAsynchronous];
}