我正在构建一个客户端-服务器应用程序,其中该应用程序正在发送一个包含大量图像的 zip 文件,php 服务器应检查是否收到该文件并返回 zip 文件中的图像数量已发送。
这是我在应用程序中的代码:
NSData *zipData = [[NSData alloc] initWithContentsOfFile:zipFile]; // zipFile contains the zip file path
NSString *postLength = [NSString stringWithFormat:@"%d", [zipData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://localhost/test.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:zipData];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300)
{
NSLog(@"Response: %@", result);
}
这是我使用 xampp 在本地主机上运行的 php 文件:
<?php
print_r($_POST);
print_r($_FILES);
?>
使用 sethttpbody 将 zip 文件附加到请求中,我正尝试在 php 中查看文件,但它始终为空,请帮助我,此外是否有权查看发送的 zip 文件打印 $_POST 和 $_FILES 如果不是正确的方法是什么,zip 文件将转换为 NSDATA,我还检查了连接是否已建立,但我对此感到很困惑。
最佳答案
虽然我不推荐它(我更愿意看到格式良好的 multipart/form-data
或 application/JSON
请求),但您可以创建你的请求是这样的:
NSData *zipData = [NSData dataWithContentsOfFile:zipFile]; // note, autorelease object
NSString *postLength = [NSString stringWithFormat:@"%d", [zipData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:zipData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *result = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSInteger statusCode = -1;
if ([response isKindOfClass:[NSHTTPURLResponse class]])
statusCode = [(NSHTTPURLResponse *)response statusCode];
NSLog(@"Response Code: %d", statusCode);
if (statusCode >= 200 && statusCode < 300)
{
NSLog(@"Response: %@", result);
}
}];
然后您可以使用 PHP 代码读取此二进制数据并将其保存到文件中:
<?php
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
$http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$handle = fopen('upload/myzip.zip', 'wb');
if ($handle == false) {
echo 'unable to open file';
exit (0);
}
$bytes = fwrite($handle, $http_raw_post_data);
if ($bytes == false)
echo 'write failed';
else
echo 'write succeeded';
fclose($handle);
?>
关于php - 将 zip 文件从 ios 应用程序发送到 php 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20097225/