使用以下代码,我设法将名为TESTTEST的jpg从我的 iOS 应用程序上传到我的服务器
- (void)saveImageToServer {
NSData *imageData = UIImageJPEGRepresentation(_profileImage, 90);
//NSString *urlString = @"URL 1/upload.php";
NSString *urlString = @"URL 2 /upload.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"_187934598797439873422234";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
[request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
[request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:@"User-Agent"];
[request setValue:@"http://google.com" forHTTPHeaderField:@"Origin"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"picture\"; filename=\"%@.jpg\"\r\n", @"TESTTEST"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);
}
这是不久前的事,我记得将该文件夹的权限设置为777
. 现在我使用相同的代码使用相同的 php 文件将图像上传到另一个域(URL 2),但这只是失败了。我也将该文件夹的权限设置为777
。此外,我已经在第一个域上测试了这个 obj-c 和 php 代码并且有效。
有人能告诉我从哪里开始寻找问题吗?它必须与服务器相关,因为它在第一个 URL 上运行良好。有没有办法可以在 PHP 中打印一些东西来帮助我调试?
这是我的 php 文件。这真的很基本,我只希望服务器上的那个图像用于测试目的:
<?php
//$target_path "./uploads/profile_image/"
$target_path = "./"; // Testing
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>