ASIHTTP:上传UIImage?

时间:2011-01-22 22:10:25

标签: iphone objective-c uiimage asihttprequest http-put

有人可以告诉我如何在Objective-c中使用ASIHTTPRequest对象上传UIImage对象吗?我需要将其转换为NSData对象吗?

(这是一个头像上传网址)

E.g. 

UIImage *toUpload = [UIImage imageNamed:@"test.jpg"]

URL: "http://www.example.com/api/users/avatar/upload?access_token=12345"
RequestType: PUT

1 个答案:

答案 0 :(得分:14)

以下是使用ASIFormRequest的示例,该示例还将尝试将图像压缩为给定的最大大小

    //Compress the image
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(yourImage, compression);
}

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:whereYourServerEndPointIs.com]];

[request addData:imageData withFileName:@"someFileName.jpeg" andContentType:@"image/jpeg" forKey:@"uploadedImage"];