【问题标题】:cant upload picture using Base64 in iphone app无法在 iPhone 应用中使用 Base64 上传图片
【发布时间】: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 中捕获的内容相同。:(

标签: iphone upload base64


【解决方案1】:

我也面临同样的问题 Red Mak 回答帮助了我。

有帮助的答案

解决了!!!实际上问题是服务器编码请求用“+”替换blanc,然后它解码用blanc替换“+”,但是在Base64中我们分配了“+”,第一步服务器什么都不做(没有找到blanc ) 但在第二个中它替换了“+”并且给出了错误的 base64 代码,

to solve that i replac "+" with ASCII equivalente like this 

:[[self base64forData:imageData]stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"].

【讨论】:

    【解决方案2】:

    我认为您的postLength 可能是错误的(您没有显示它是如何计算的以及它是什么类型)。改为这样做:

    [request
        setValue:[NSString stringWithFormat:@"%u", [postData length]] 
        forHTTPHeaderField:@"Content-Length"
    ];
    

    【讨论】:

    • 已解决!!!实际上问题是服务器编码请求用“+”替换blanc,然后它解码用blanc替换“+”,但是在Base64中我们分配了“+”,第一步服务器什么都不做(没有找到blanc ( %2B"]。希望对某人有所帮助。感谢 DarkDust 的帮助;)
    猜你喜欢
    • 2013-11-03
    • 2015-08-22
    • 1970-01-01
    • 2020-06-26
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2012-12-31
    相关资源
    最近更新 更多