23
我一直在將UIImage上傳到網絡服務器。問題是,圖像從不出現在服務器上。來自HTML文件的普通POST可以工作。我認爲這是我的Objective-C代碼中的一個問題。將圖像從iOS上傳到PHP
這裏是我的Objective-C代碼:
NSData *imageData = UIImagePNGRepresentation(delegate.dataBean.image);
NSString *urlString = [NSString stringWithFormat:@"%@test.php", delegate.dataBean.hosterURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog([NSString stringWithFormat:@"Image Return String: %@", returnString]);
這是我的PHP代碼:
<?php
$uploaddir = 'uploads/';
$file = basename($_FILES['uploadedfile']['name']);
$uploadfile = $uploaddir . $file;
echo "file=".$file; //is empty, but shouldn't
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) {
echo $file;
}
else {
echo "error";
}
?>
的print_r($ _ FILES)又有什麼節目 – 2012-07-10 13:01:20
它顯示一個空數組: 陣列 ( ) – 2012-07-10 13:05:34
$ _FILES應該被默認定義。但是如果有上傳,它不應該是空的。 – 2012-07-10 13:13:39