Hochladen großer Bilder mit Base64 und JSON
Ich benutze diese Funktion, um ein Bild mit auf einen Server hochzuladenJSON
. Dazu konvertiere ich zunächst das Bild inNSData
und dann zuNSString
mitBase64
. Die Methode funktioniert gut, wenn das Bild nicht sehr groß ist, aber wenn ich versuche, ein 2-MB-Bild hochzuladen, stürzt es ab.
Das Problem ist, dass der Server mein Bild nicht empfängt, obwohl diedidReceiveResponse
Methode heißt ebenso wie diedidReceiveData
was zurückkehrt(null)
. Zuerst dachte ich, es sei ein Timeout-Problem, aber selbst wenn ich es auf 1000.0 setze, funktioniert es immer noch nicht. Irgendeine Idee? Vielen Dank für Ihre Zeit!
Hier ist mein aktueller Code:
- (void) imageRequest {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.myurltouploadimage.com/services/v1/upload.json"]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [NSString stringWithFormat:@"%@/design%i.png",docDir, designNum];
NSLog(@"%@",path);
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
[Base64 initialize];
NSString *imageString = [Base64 encode:imageData];
NSArray *keys = [NSArray arrayWithObjects:@"design",nil];
NSArray *objects = [NSArray arrayWithObjects:imageString,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(@"Image uploaded");
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}