6

有人可以告诉我如何在 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
4

1 回答 1

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"];
于 2011-01-22T22:40:07.823 回答