【发布时间】:2011-11-08 08:04:00
【问题描述】:
我之前在这个论坛上问过这个问题,但它被关闭了,我不知道为什么,所以我再次发布我的问题。 在 iphone 应用程序中,我必须使用 Base64 编码上传图片,但是当我查看服务器时,图片全是白色(大小 = 0x0,54 KO),我确定我的图片的 Base64 编码是正确的,因为我有php脚本,我使用它,图片正常显示。 这是用于上传的php代码:
<?php
$filename = "photo_to_upload.jpg";
$handle = fopen($filename, "r");
$imgbinary = fread($handle, filesize($filename));
$data = base64_encode($imgbinary);
fclose($handle);
?>
<img src="./<?php echo $filename ?>" />
<form action="http://host" method="POST">
<input type="hidden" name="data" value="<?php echo $data?>">
<input type="submit" value="envoyer" />
</form>
和我使用的 Xcode:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"photo_to_upload" ofType:@"jpg"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSURLResponse* response;
NSError* error=nil;
NSMutableData *postData=[[NSMutableData alloc]init];
[postData appendData:[@"data=" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[self base64forData:imageData]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"HOST"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
想你有什么帮助。
【问题讨论】:
-
size = 0x0 ,54 KO是什么意思?大小是 0 字节吗?是什么让您认为您的base64forData:方法可以正常工作?您是否将输出打印到控制台并将其与您的 PHP 脚本进行比较? (您的 PHP 脚本工作的事实并不能验证您的 Objective-C 代码的工作) -
想你重播。 0x0 是宽度 x 高度和 54 K 八位字节。关于我的 base64 编码,我将“value="”替换为“base64forData”函数的返回值,图片上传正确。
-
我很确定 Content-Type
application/x-www-form-urlencoded在这里是错误的(并且您需要 Content-Disposition),但我不知道正确的值。使用 Wireshark 查看 PHP 脚本发送的标头,并在 Objective-C 代码中使用相同的值。 -
这是 Wireshark 结果的一部分:Content-Length: 79805\r\n
-
抱歉,我无法编辑帖子并且我复制了错误的值。这是 php 脚本中 wireshark 捕获的内容类型:“Content-Type: application/x-www-form-urlencoded\r\n” 与 iphone 中捕获的内容相同。:(