[英]uploading image picker with AFNetworking
对不起,对不起。 我还不太了解。
所以目前我有代码:
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL
URLWithString:@"http://xyz.co.uk/zyx/imageupload.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"image/png"
forHTTPHeaderField:@"Content-type"];
[request setValue:[NSString stringWithFormat:@"%lu",
(unsigned long)[imageData length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[self imageDataToSend]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
imageupload.php
: <?php
$handle = fopen("image.png", "wb"); // write binary
fwrite($handle, $HTTP_RAW_POST_DATA);
fclose($handle);
print "Received image file.";
?>
将照片上传到我的网站...完美...不!
我注意到了一些问题。
然后我朝这个方向看。 一切都很好,直到我意识到它实际上是垃圾,并且在尝试上传它时收到一百万个错误。 每个人都还告诉我,我走错了方向: “ ASIHTTPRequest很旧。您应该使用AFNetworking” 。
我现在正尝试使用AFNetworking,但事实证明这非常困难! 我完全看不到它与ASIHTTPRequest有何相似之处。
有人可以用AFNetwork帮我做些奇怪的事情吗? 或者是一种将图像数据上传到我的php文件的完整方法。
这是使用AFNetworking上传照片的示例-ZodioAPIClient是我的AFHTTPClient子类。 您将要继承AFHTTPClient的子类(通常创建一个singleton来进行如下操作)。 文件名当然是您选择的,真正重要的是附加NSData。 请注意,这是针对AFNetworking <2.0。 2.0的结构不同,但是如果您能在下面理解,则可以轻松地将其迁移到2.0。
这些步骤是(这适用于所有AFNetworking操作,并带有一些用于照片数据的特殊步骤):
NSData *photo = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);
NSMutableURLRequest *addPhotoRequest = [[YourAFHTTPClientSubclass sharedClient] multipartFormRequestWithMethod:@"POST" path:addPhotoPath parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData)
{
[formData appendPartWithFileData:photo name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
}];
AFJSONRequestOperation *addPhotoRequestOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:addPhotoRequest
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
DDLogVerbose(@"in add photo success block");
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
DDLogVerbose(@"request that errored: %@", request);
DDLogVerbose(@"Request failed with error: %@, %@", error, error.userInfo);
DDLogVerbose(@"the response I got was: %@", JSON);
}];
[addPhotoRequestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
DDLogVerbose(@"Total progress: %f", (totalBytesWritten * 1.0f)/(totalBytesExpectedToWrite * 1.0f));
}];
[[YourAFHTTPClientSubclass sharedClient] enqueueHTTPRequestOperation:addPhotoRequestOperation];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.