对不起我的无知。我还不太了解它。
所以目前我有代码:
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.";
?>
将照片上传到我的网站......完美......不!
我注意到了一些问题。
然后我看向this。直到我意识到它实际上是垃圾并且我在尝试上传它时收到了一百万个错误,这一切都很好。每个人都告诉我,我的方向错误“ASIHTTPRequest已经过时了。你应该使用AFNetworking”。
我现在正在尝试使用AFNetworking,但事实证明这非常困难!我根本看不出它与ASIHTTPRequest的相似之处。
任何人都可以帮助我用AFNetwork做同样的事情。或者整个人都知道将图像数据上传到我的php文件的方法。
答案 0 :(得分:0)
以下是使用AFNetworking进行照片上传的示例 - ZodioAPIClient是我的AFHTTPClient子类。你想要AFHTTPClient的子类(通常创建一个单例来做下面的事情)。文件名当然是您的选择,真正重要的是附加NSData。注意,这适用于AFNetworking&lt; 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];