iPhone base64损坏时,张贴到php脚本


iPhone base64 corrupted when posted to php script

在我的应用程序中,用户作物那里的图片,我编码为base64字符串,并将其发送到我的php脚本。我正在使用NSData+base64类然而,当应用程序去检索字符串再次转换回图片我得到这个错误:

Jan  8 14:21:33 Vessel.local Topic[11039] <Error>: ImageIO: JPEG Corrupt JPEG data:214        extraneous bytes before marker 0x68  Jan  8 14:21:33 Vessel.local Topic[11039] <Error>: ImageIO: JPEG Unsupported marker type 0x68

下面是我发送数据的代码:

 NSString *urlString = [NSString stringWithFormat:@"http://myurl.php"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url                cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
NSString *param = [NSString stringWithFormat:@"username=%@&password=%@&email=%@&quote=%@&pic=%@",user,password,email,quote,pic];
[request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request  delegate:self startImmediately:YES];

这是当我得到它回到另一个视图控制器,并试图把它变成一个图像

 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
homeData = [NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
NSString *decodeString = [[homeData objectAtIndex:0]objectForKey:@"profile_pic" ];
decodeString = [decodeString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
int returnNUM = [decodeString length];
NSLog(@"RETURN STRING=%d",returnNUM);
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:decodeString]];
profilepic = [[UIImageView alloc]initWithFrame:CGRectMake(5, 4, 120, 120)];
profilepic.image = [UIImage imageWithData:data];
UIGraphicsBeginImageContextWithOptions(profilepic.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:profilepic.bounds cornerRadius:80.0] addClip];
[pic drawInRect:profilepic.bounds];
profilepic.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view addSubview:profilepic];
 }

我怎么能防止图像被破坏,一旦我发布它..或一旦我得到它回来我怎么能清理它或防止腐败正在发生!这简直要把我逼疯了……如果能给出一个清晰的答案,并附上一些代码,我将不胜感激。由于

这是我用来在发送之前将图像转换为base64的代码。

    NSData *imageData = UIImageJPEGRepresentation(crop, 1.0);
    NSString *baseString = [imageData base64EncodedString];
    int original =[baseString length];
    NSLog(@"orignal String=%d",original);
    [self register:username.text withPass:password.text withEmail:email.text withQuote:quote.text withPic:baseString];

为什么要做" stringbytrimingcharactersinset "调用?在我看来,这似乎是为了删除编码图像可能需要的字符…

编辑包括一些代码的例子,我使用正确嵌入一对图片到一个http表单提交到一个php页面。

我在NSMutableData上使用下面的Category…

NSMutableData+HTTP.h

@interface NSMutableData (HTTP)
-(void)appendFileAtPath:(NSString*)fullFilePath withFormKey:(NSString*)formKey withSuggestedFileName:(NSString*)suggestedFileName boundary:(NSData*)boundary;
-(void)appendKey:(NSString*)key value:(NSString*)value boundary:(NSData*)boundary;
@end

NSMutableData+HTTP.m

#import "NSMutableData+HTTP.h"
@implementation NSMutableData (HTTP)
//use for attaching a file to the http data to be posted
-(void)appendFileAtPath:(NSString*)fullFilePath withFormKey:(NSString*)formKey withSuggestedFileName:(NSString*)suggestedFileName boundary:(NSData*)boundary{
    [self appendData:boundary]; 
    [self appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name='"%@'"; filename='"%@'"'r'n", formKey, suggestedFileName] dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:[@"Content-Type: application/octet-stream'r'n'r'n" dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:[NSData dataWithContentsOfFile:fullFilePath]];
    [self appendData:[@"Content-Encoding: gzip'r'n'r'n" dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:boundary]; 
}
//use for attaching a key value pair to the http data to be posted
-(void)appendKey:(NSString*)key value:(NSString*)value boundary:(NSData*)boundary{    
    [self appendData:boundary]; 
    [self appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name='"%@'"'r'n'r'n", key] dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:boundary]; 
}
@end

然后在我的代码,创建一个http表单提交我做以下附加一对图像和键值对(通过上面的类别方法)到表单…(注意:我没有包括NSURLConnectionDelegate方法,如果你想跟踪表单提交的进度,你需要实现这些方法。)

NSString *boundaryString = @"0xKhTmLbOuNdArY";
NSData *boundaryData = [[NSString stringWithFormat:@"'r'n--%@'r'n", boundaryString] dataUsingEncoding:NSUTF8StringEncoding];
NSString *phpReceiverURL = @"http://www.someurl.com/somephppage.php";
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setTimeoutInterval:30];
[theRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[theRequest setHTTPShouldHandleCookies:NO];
[theRequest setURL:[NSURL URLWithString:phpReceiverURL]];
[theRequest setHTTPMethod:@"POST"]; 
[theRequest addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundaryString] forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
//add some image files to the form
[body appendFileAtPath:[imagePath stringByAppendingPathComponent:@"cat.jpg"] 
    withFormKey:@"cat"  
    withSuggestedFileName:@"received-cat.jpg"
    boundary:boundaryData
];
[body appendFileAtPath:[imagePath stringByAppendingPathComponent:@"dog.jpg"] 
    withFormKey:@"dog"  
    withSuggestedFileName:@"received-dog.jpg"
    boundary:boundaryData
];
//add some key value pairs to the form
[body appendKey:@"testkeyone" value:@"testvalueone" boundary:boundaryData]; 
[body appendKey:@"testkeytwo" value:@"testvaluetwo" boundary:boundaryData]; 
// setting the body of the post to the reqeust
[theRequest setHTTPBody:body];
//create the connection
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

还要注意,我还没有在我的应用程序之外测试过这个,所以我可能忘记了一些东西(比如"imagePath",我没有在上面的例子中定义-你必须为你的图像指定一个路径),但它应该给你一个好主意,如何将一些图像附加到一个表单提交到一个php页面。

希望这对你有帮助!