cant upload picture using Base64 in iphone app

风流意气都作罢 提交于 2020-01-01 17:07:14

问题


i ask this before in this forum but it was closed i dont know why, so i post my question again. in an iphone app i have to upload a picture using Base64 encoding, but when i look in the server the picture is all white ( size = 0x0 ,54 KO ), im sure that my Base64 encode of my pic is correct because i have a php script ,i use it and the picture appear normally. here is the php code used to upload :

<?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>

and the Xcode i use this :

 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];    

think you for any help.


回答1:


I too face the same Issue Red Mak Answer Helped me.

Answer That Helped

SOLVED !!! in fact the problem was that server encode the request replacing the blanc with "+" after that it decode replacing the "+" with blanc ,but in Base64 we have allot of "+" ,the first step server do nothing( no blanc find) but in the seconde it replace the "+" and that give a wrong base64 code ,

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

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



回答2:


I assume your postLength is probably wrong (you're not showing how it was calculated and what type it is). Do this instead:

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


来源:https://stackoverflow.com/questions/8047481/cant-upload-picture-using-base64-in-iphone-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!