Вопрос

I am currently developing for iOS 7, but to keep compatibility I am making sure everything works in iOS 6 as well(of course). My multipart/form-data works in iOS 7 as expected, but in iOS 6 my server is not receiving any files(the connection is made, just no files). Is there something I am missing?

// Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"%@.jpg\"\r\n", deviceId] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//workaround added here

[request setHTTPBody:body];

//make request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start]; 

Edit: The below line was added to the above code as a workaround, but I don't think this is the "correct" way to perform this.

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
Это было полезно?

Решение

It seems that I have accidentally deleted a line of code. Looking through past commits I found my problem. I deleted the Content-Type line.

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];// Here was my problem
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"%@.jpg\"\r\n", deviceId] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top