我已经使用AFNetwork搜索了很多工作上传代码,但没有运气。我想出了这个代码,我从2个不同的网站得到它:使用AFNetwork上传图片
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"1.png"]);
NSURL *url = [NSURL URLWithString:@"http://localhost/project"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"google" fileName:@"1.png" mimeType:@"image/png"];
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
} failure:nil];
[operation start];
但我得到的是“IP地址:(空)”。我的PHP方面是这样的:
function upload(){
$uploaddir = 'uploads/';
$file = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
sendResponse(200, 'Upload Successful');
return true;
}
sendResponse(403, 'Upload Failed');
return false;
}
我真的很感激一点帮助。
thanx的代码,只有一两件事,当我使用HTML浏览测试我的PHP代码,我有这样的: 和我的图像名称是1.png。我有一个使用这些设置itemData和字典的问题。你能帮我吗? – AliBZ
你只需要在NSData中转换你的UIImage。 with self.itemData = UIImagePNGRepresentation(yourUIImageInstanc E); 。在我的代码中,self.itemData是一个Property类型的NSData。 – LombaX
你能再解释一次吗?我现在不明白你的问题。如果你想用浏览器检查你的php代码,你必须用一个表单和一个输入类型文件(你已经发布的行)制作一个简单的页面。表单方法是post和action是php接收者页面的地址。
然后只需选择文件并上传 – LombaX