使用以下代码,我设法将一个名为 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!";
}
?>
我会做两件事:
-
在您的 PHP 文件中添加更多
echo
ES 以检查 $_GET/$_POST/$_FILES 以查看一切正常; 还可以使用realpath
查看您的target_path
解析为什么; -
使用该
NSError
参数sendSynchronousRequest
以查看请求客户端会发生什么情况:NSError* error = nil; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; NSLog(@"%@",[error localizedDescription]);