0

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

1 回答 1

0

看来我不小心删除了一行代码。回顾过去的提交,我发现了我的问题。我删除了 Content-Type 行。

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]];
于 2013-10-03T16:34:58.253 回答